ASP.NET MVC 和 Web Api 在同一项目中,重复的 http 响应 header 值
ASP.NET MVC and Web Api in the same project, duplicate http response header values
我有一个 ASP.NET Web 项目,结合了 MVC 5 和 Web Api 2。该项目包含一个 web.config 文件和一些自定义 http headers在 system.webserver 部分下定义。这些 headers 对于 MVC 请求工作正常,但对于 Api 请求有一些重复值。
<customHeaders>
<clear />
<add name="Expires" value="-1" />
... other headers
</customHeaders>
所有 API 请求都有重复的 Http headers 像 Cache-Control,像这样的 Expires 和 Pragma。
Cache-Control: no cache, no cache
Expires: -1,-1
Web API 框架似乎默认设置了这些值。是否可以禁用默认 Api headers 并使用配置设置或完全忽略 Api 请求的配置设置?有好的解决方案吗?
像上面那样清除 customHeaders 元素或通过在添加之前先删除它来覆盖它们也不起作用。
您可以解决此问题。从 web.config 中删除 customHeaders 标签。
在您的 MVC 5 项目中,添加自定义操作过滤器属性。
public class AddHeadersFilterAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("header", "headerValue");
base.OnActionExecuting(filterContext);
}
}
使用此属性装饰 MVC 5 控制器的 BaseController。
这应该可以解决您的问题并让 Web API 2 正常运行。
我有一个 ASP.NET Web 项目,结合了 MVC 5 和 Web Api 2。该项目包含一个 web.config 文件和一些自定义 http headers在 system.webserver 部分下定义。这些 headers 对于 MVC 请求工作正常,但对于 Api 请求有一些重复值。
<customHeaders>
<clear />
<add name="Expires" value="-1" />
... other headers
</customHeaders>
所有 API 请求都有重复的 Http headers 像 Cache-Control,像这样的 Expires 和 Pragma。
Cache-Control: no cache, no cache
Expires: -1,-1
Web API 框架似乎默认设置了这些值。是否可以禁用默认 Api headers 并使用配置设置或完全忽略 Api 请求的配置设置?有好的解决方案吗?
像上面那样清除 customHeaders 元素或通过在添加之前先删除它来覆盖它们也不起作用。
您可以解决此问题。从 web.config 中删除 customHeaders 标签。 在您的 MVC 5 项目中,添加自定义操作过滤器属性。
public class AddHeadersFilterAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.HttpContext.Response.AddHeader("header", "headerValue");
base.OnActionExecuting(filterContext);
}
}
使用此属性装饰 MVC 5 控制器的 BaseController。 这应该可以解决您的问题并让 Web API 2 正常运行。