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()
lacks an override that allows you to specify the Content-Type
, and ActionResult
and friends don't seem to expose anything, either. The motivation is obviously to work around Internet Explorer guessing the "correct" encoding type, which I in turn want to do to avoid UTF-7 XSS attacks.
Asked
Active
Viewed 1.4k times
13

Benjamin Pollack
- 27,594
- 16
- 81
- 105
3 Answers
22
Maybe this in your web.config will do the magic?
<configuration>
<system.web>
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
</system.web>
</configuration>

Michael Haren
- 105,752
- 40
- 168
- 205

Mickel
- 6,658
- 5
- 42
- 59
-
4+1; I like this better than my suggestion, although I believe both will work. – Craig Stuntz Nov 16 '09 at 18:48
-
2Just for reference, the default of both requestEncoding and responseEncoding is utf-8 anyway. See [MSDN](http://msdn.microsoft.com/en-us/library/hy4kkhe0.aspx) – Appetere Mar 16 '12 at 09:08
-
1Updated link to [MSDN](http://msdn.microsoft.com/en-gb/library/hy4kkhe0(v=vs.100).aspx) – Liam Oct 28 '14 at 12:37
2
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.

Craig Stuntz
- 125,891
- 12
- 252
- 273
-
That'd work great if I were running in integrated pipeline mode, but I don't believe I'm allowed to muck with headers quite that way on IIS6 and earlier, am I? – Benjamin Pollack Nov 16 '09 at 18:37
-
You can certainly add them; we've tested this, and it works. I haven't tried modifying an existing header, though. Give it a shot; it's easy to test. – Craig Stuntz Nov 16 '09 at 18:48
0
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.

iPath ツ
- 2,468
- 20
- 31