curious1
curious1

Reputation: 14717

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.

Upvotes: 10

Views: 19744

Answers (1)

ntl
ntl

Reputation: 1299

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>

Upvotes: 14

Related Questions