For guys using ASP.NET MVC
One option is to use Action Filter on controllers/actions. This does slow down responses from the server a bit but I don't know the exact numbers. But it's a clean way to do it:
///
/// Represents an attribute that is used to add HTTP Headers to a Controller Action response.
///
public class HttpHeaderAttribute : ActionFilterAttribute
{
///
/// Gets or sets the name of the HTTP Header.
///
/// The name.
public string Name { get; set; }
///
/// Gets or sets the value of the HTTP Header.
///
/// The value.
public string Value { get; set; }
///
/// Initializes a new instance of the class.
///
/// The name.
/// The value.
public HttpHeaderAttribute(string name, string value) {
Name = name;
Value = value;
}
public override void OnResultExecuted(ResultExecutedContext filterContext) {
if(!filterContext.HttpContext.Response.Headers.AllKeys.Contains(Name, StringComparer.OrdinalIgnoreCase))
filterContext.HttpContext.Response.AppendHeader(Name, Value);
base.OnResultExecuted(filterContext);
}
}
However, the absolutely best and cleanest way for me is using web.config
. Put this code into <system.webServer>
element:
<httpProtocol>
<customHeaders>
<!--
http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
Uncomment to serve cross-domain ajax requests
<add name="Access-Control-Allow-Origin" value="*" />
-->
<!--
Force the latest IE version, in various cases when it may fall back to IE7 mode
github.com/rails/rails/commit/123eb25#commitcomment-118920
Use ChromeFrame if it's installed for a better experience for the poor IE folk
-->
<add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
<!--
Allow cookies to be set from iframes (for IE only)
If needed, uncomment and specify a path or regex in the Location directive
<add name="P3P" value="policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"" />
-->
<!-- A little extra security (by obscurity) -->
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
Obviously this only works in IIS7+.
HTH