Adding “charset” to all ASP.NET MVC HTTP responses

Deadly 提交于 2019-12-03 05:48:22
Mickel

Maybe this in your web.config will do the magic?

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

You could write an attribute for it:

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

Feel free to make it a bit smarter, but that's the general idea. Add it to your base controller class and your whole app is covered.

In MVC 5 this can do the trick:

public class ResponseCharset : ActionFilterAttribute
{
    private string Charset;

    public ResponseCharset(string charset = "utf-8") {
        Charset = charset;
    }

    public override void OnActionExecuted(HttpActionExecutedContext filterContext)
    {
        filterContext.Response.Content.Headers.ContentType.CharSet = Charset;
    }
} 

Usage:

public class OrderDetailsController : ApiController
{
    [ResponseCharset("utf-8")]  // can be windows-1251 etc.
    public Object Get(string orderId)
    {
       // ....
    }
}

Based on @craig-stuntz 's idea.

Of course you need to ensure you give right response encoding i.e. content's encoding should match to that, specified in ResponseCharset attribute.

It helped me a lot when I was testing some mvc code with Chrome, because it does not specify encoding in the accept header.

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