Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 998
curious1 Avatar asked Aug 15 '14 03:08

curious1


1 Answers

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>
like image 195
ntl Avatar answered Oct 05 '22 22:10

ntl