2

我有一个带有 nvarchar 数据的 MS SQL Server 数据库,特别是一个带有“★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)),但没有任何帮助。这样做的正确方法是什么?

4

1 回答 1

6

'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;
于 2015-03-16T06:10:41.130 回答