How to set custom headers with web.config?

Ray Cheng picture Ray Cheng · Sep 24, 2014 · Viewed 21.7k times · Source

I have the following in the web.config, but after it's published to IIS 7.5 on the server, they couldn't be find under IIS -> HTTP Response Headers.

What I found is that the web.config on server doesn't have those entries either, but they were there before publishing. So I can only say the publishing process stripped them out, but there is nothing in the web.config transform files that removes them. So why are they gone from the published `web.config'?

 <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Answer

pim picture pim · Mar 19, 2016

Are you sure that the web.config is the best place for this? I tend to prefer Custom ActionFilter's. This affords you the opportunity to pick and choose when (on what methods) you want the logic to occur and also offers far more control (specially exception handling, what to do at the various stages of the Action lifecycle).

Microsoft recommends using this approach for invocations that occur before Action execution.

Some example code

    public class CustomFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //add in your custom headers
            filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
            filterContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS");

            base.OnActionExecuting(filterContext);
        }

        public void OnException(ExceptionContext filterContext)
        {
          //do some cool exception handling here
        }
    }