10

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 Answer 1

14

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>
Sign up to request clarification or add additional context in comments.

1 Comment

I have try 'Response.Charset = ""' but my file always downloaded as utf-8. How can change it if the file is IBM-737 for example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.