How to set custom headers with web.config?
Asked Answered
X

1

14

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>
Xiphoid answered 24/9, 2014 at 18:5 Comment(2)
Do you have different configs for Debug and Release?Polyandrous
Agree with Jason, check your web.config transforms.Tamra
P
2

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
        }
    }
Pettus answered 19/3, 2016 at 19:26 Comment(1)
Don't you think better would be to use Result filter instead of Action?Executrix

© 2022 - 2024 — McMap. All rights reserved.