ASP.NET MVC:返回FileResult时如何设置编码

cur*_*us1 7 asp.net-mvc character-encoding asp.net-mvc-4

在我的控制器中,我有以下内容将存储在CSHTML文件中的HTML片段发送到前面.

    public FileResult htmlSnippet(string fileName)
    {
        string contentType = "text/html";
        return new FilePathResult(fileName, contentType);
    }
Run Code Online (Sandbox Code Playgroud)

fileName如下所示:

/file/abc.cshtml

现在让我感到困扰的是,这些HTML代码段文件具有西班牙语字符,当它们显示在页面中时看起来不正确.

感谢致敬.

ntl*_*ntl 11

首先确保您的文件是UTF-8编码的:

查看讨论.

如何设置响应的编码:

我想你可以这样做:

 public FileResult htmlSnippet(string fileName)
    {
        string contentType = "text/html";
        var fileResult = new FilePathResult(fileName, contentType);
        Response.Charset = "utf-8"; // or other encoding
        return fileResult;
    }
Run Code Online (Sandbox Code Playgroud)

其他选项是创建Filter属性,然后您可以使用此属性标记单独的控制器或操作(或将其添加到全局过滤器):

public class CharsetAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.Headers["Content-Type"] += ";charset=utf-8";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想为所有HTTP响应设置编码,您也可以尝试在web.config中设置编码.

<configuration>
  <system.web>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
  </system.web>
</configuration>
Run Code Online (Sandbox Code Playgroud)