如何在web.config中设置自定义头?

14

在 web.config 中我有以下内容,但是当它被发布到服务器上的 IIS 7.5 后,在 IIS -> HTTP 响应标头 下无法找到它们。

我发现服务器上的 web.config 也没有这些条目,但在发布之前它们是存在的。因此,我只能说发布过程将它们删除了,但是转换文件中没有任何删除它们的内容。那么为什么它们会从发布的 '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>

1
你是否有针对Debug和Release的不同配置? - Jason Portnoy
同意Jason的观点,检查你的web.config转换。 - Nick
1个回答

2

你确定web.config是最好的地方吗?我更喜欢自定义ActionFilter。这样可以让你选择在哪些方法上执行逻辑,还提供了更多的控制(特别是异常处理,在Action生命周期的各个阶段要做什么)。

Microsoft 建议 在Action执行之前使用此方法进行调用。

一些示例代码

    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
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接