NancyFx:将默认字符集设置为utf8

Ami*_*iri 6 c# nancy

我在我的cshtml文件中有这个片段:

Expires on: @Model.EndDate.ToString("MMM dd yyyy")
Run Code Online (Sandbox Code Playgroud)

我在回复中得到了这个:

HTTP/1.1 200 OK
Content-Type: text/html

...
Expires on: ?????™ 05 2013
Run Code Online (Sandbox Code Playgroud)

如何告诉Nancy默认使用UTF8进行响应?


编辑:为了澄清,这不是一个本地化问题,输出已经本地化 - 只是本地化的UTF8字符串被发送到没有UTF8字符集声明的客户端,所以它被搞砸,试图将其视为latin1 .

我要找的是这个:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8

...
Run Code Online (Sandbox Code Playgroud)

而且我不想单独为每个响应指定它.

我正在使用NancyFx Web框架

Kam*_*yar 8

如果要在模块的响应中指定UTF8字符集声明,可以定义After拦截器.以下是如何在模块的构造函数中定义After Interceptor:

After += ctx =>
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

您还可以在引导程序中定义应用程序级挂钩:

pipelines.AfterRequest += (ctx) => { ... };
Run Code Online (Sandbox Code Playgroud)

更新:根据评论,最好的方法是在钩子中使用以下代码:

if (ctx.Response.ContentType == "text/html")
    ctx.Response.ContentType = "text/html; charset=utf-8";
Run Code Online (Sandbox Code Playgroud)

  • 好的,正确的方法是使用`Response.ContentType`.由于只显示HtmlResponse不处理字符集,因此可以将其限制为:if(ctx.Response.ContentType =="text/html")ctx.Response.ContentType ="text/html; charset = utf8 "`.如果你编辑你的答案我会接受它:-) (2认同)