向 Web API 中的所有响应添加自定义标头 [英] Add custom header to all responses in Web API
问题描述
简单的问题,我相信它有一个简单的答案,但我找不到.
Simple question, and I am sure it has a simple answer but I can't find it.
我正在使用 WebAPI,我想将自定义标头发送回所有响应(开发人员出于同步目的而请求的服务器日期/时间).
I am using WebAPI and I would like to send back a custom header to all responses (server date/time requested by a dev for syncing purposes).
我目前正在努力寻找一个清晰的例子,说明如何在一个地方(通过 global.asax 或另一个中心位置)我可以为所有响应显示一个自定义标题.
I am currently struggling to find a clear example of how, in one place (via the global.asax or another central location) I can get a custom header to appear for all responses.
答案已接受,这是我的过滤器(几乎相同)和我添加到 WebApi 配置的注册功能的行.
Answer accepted, here is my filter (pretty much the same) and the line i added to the Register function of the WebApi config.
注意:DateTime 的东西是 NodaTime,没有真正的理由只是对它感兴趣.
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Content.Headers.Add("ServerTime", Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()).ToString());
}
配置行:
config.Filters.Add(new ServerTimeHeaderFilter());
推荐答案
为此,您可以使用自定义 ActionFilter (System.Web.Http.Filters
)
For that you can use a custom ActionFilter (System.Web.Http.Filters
)
public class AddCustomHeaderFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Headers.Add("customHeader", "custom value date time");
}
}
然后,您可以通过在 Global.asax 的配置中添加此过滤器来将过滤器应用于所有控制器的操作,例如:
You can then apply the filter to all your controller's actions by adding this in the configuration in Global.asax for example :
GlobalConfiguration.Configuration.Filters.Add(new AddCustomHeaderFilter());
您也可以将过滤器属性应用于您想要的操作,而无需全局配置行.
You can also apply the filter attribute to the action that you want without the global cofiguration line.
这篇关于向 Web API 中的所有响应添加自定义标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!