Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom headers with web.config?

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>
like image 487
Ray Cheng Avatar asked Sep 24 '14 18:09

Ray Cheng


People also ask

Where do I put custom headers in Web config?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

How do I set HTTP headers?

In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name. In the Value box, type the custom HTTP header value.


1 Answers

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
        }
    }
like image 65
pim Avatar answered Sep 19 '22 06:09

pim