代码之家  ›  专栏  ›  技术社区  ›  Benjamin Pollack Stefan Rusek

向所有ASP.NET MVC HTTP响应添加“字符集”

  •  10
  • Benjamin Pollack Stefan Rusek  · 技术社区  · 16 年前

    是否有一种简单的方法来指定ASP.NET MVC应用程序要具有的所有“正常”视图 charset=utf-8 附于 Content-Type View() 缺少允许您指定 ,及 ActionResult 而且朋友们似乎也不会暴露任何东西。其动机显然是围绕InternetExplorer猜测“正确”的编码类型,而我也希望这样做以避免UTF-7XSS攻击。

    3 回复  |  直到 16 年前
        1
  •  22
  •   shsteimer    13 年前

    也许这在你的web.config中会起到神奇的作用?

    <configuration>
      <system.web>
        <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
      </system.web>
    </configuration>
    
        2
  •  2
  •   Craig Stuntz    16 年前

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

    尽管可以让它变得更聪明一点,但这只是一般的想法。将其添加到基本控制器类中,即可覆盖整个应用程序。

        3
  •  0
  •   iPath ツ    11 年前

    在MVC 5中,这可以实现以下目的:

    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;
        }
    } 
    

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

    基于@craig stuntz的想法。

    当然,您需要确保给出正确的响应编码,即内容的编码应该与ResponseCharset属性中指定的匹配。

    推荐文章