ASP.NET MVC: how to set encoding when returning FileResult

坚强是说给别人听的谎言 提交于 2020-01-03 09:06:07

问题


In my controller, I have the following to send HTML snippet stored in CSHTML files to the front.

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

The fileName looks like the following:

/file/abc.cshtml

What troubles me now is that these HTML snippet files have Spanish characters and they don't look right when they are displayed in pages.

Thanks and regards.


回答1:


First ensure that your file is UTF-8 encoded:

Check this discussion.

What about setting encoding for responses:

I think you may do it like this:

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

Other option is to create Filter attribute, then you can mark separate controllers or actions with this attribute (or add it to global filters):

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

If you wanna to set encoding for all HTTP responses you may try to set encoding in web.config as well.

<configuration>
  <system.web>
    <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
  </system.web>
</configuration>


来源:https://stackoverflow.com/questions/25320674/asp-net-mvc-how-to-set-encoding-when-returning-fileresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!