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

前端 未结 3 530
醉话见心
醉话见心 2021-02-07 21:58

Is there an easy way to specify all \"normal\" views is an ASP.NET MVC app are to have charset=utf-8 appended to the Content-Type? View()

3条回答
  •  耶瑟儿~
    2021-02-07 22:51

    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.

提交回复
热议问题