ASP.NET MVC: How to Set Encoding on FileResult Return

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

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

The file name is as follows:

/file/abc.cshtml

What bothers me is that these HTML snippet files have Spanish characters and they don't look right when they appear on pages.

Thank you and welcome.

+5
source share
1 answer

First, make sure your file is encoded in UTF-8 encoding:

Mark this discussion.

How about setting the encoding for answers:

I think you can 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; } 

Another option is to create a Filter attribute, then you can mark individual 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 want to set the encoding for all HTTP responses, you can also try setting the encoding in web.config.

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

Source: https://habr.com/ru/post/1200377/


All Articles