在 Delphi 中将非 ASCII 字符纳入 WebBroker 响应

Getting non-ASCII characters into WebBroker response in Delphi

我有一个 MS SQL 服务器数据库,其中包含 nvarchar 数据,特别是其中包含“★ABC★”的数据字段。我的 Delphi 桌面应用程序可以很好地显示它,但是来自我在 Delphi XE4 中使用 TDataSetTableProducer 生成响应的 WebBroker 应用程序的相同数据不起作用。这是最基本的示例代码:

procedure TWebModule1.WebModule1TestAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.ContentEncoding := 'text/plain; charset="UTF-8"';
  Response.Content := '<!DOCTYPE html>'
  + '<html>'
  + '<body>'
  + '<p> ★ABC★ </p>'
  + '</body>'
  + '</html>'
end;

在网络浏览器中查看时,结果为“?ABC?”。我已经尝试了很多东西(包括 UTF-16 和在响应前加上 Char($FEFF)),但没有任何帮助。正确的做法是什么?

'text/plain; charset="UTF-8"' 不是 Response.ContentEncoding 属性 的有效值。您需要将其放在 Response.ContentType 属性 中。此外,它应该使用 text/html 而不是 text/plain:

Response.ContentType := 'text/html; charset="UTF-8"';

如果浏览器仍然无法正确显示数据,您可能需要使用 Response.ContentStream 属性 而不是 Response.Content 属性,因此您可以自己编码UTF-8数据:

procedure TWebModule1.WebModule1TestAction(Sender: TObject;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
  Response.ContentType := 'text/html; charset="UTF-8"';
  Response.ContentStream := TStringStream.Create(
    '<!DOCTYPE html>'
    + '<html>'
    + '<body>'
    + '<p> ★ABC★ </p>'
    + '</body>'
    + '</html>',
    TEncoding.UTF8);
end;