问题描述
简单的问题,我相信有一个简单的答案,但我不能找到它。
我使用的WebAPI,我想以一个自定义标题发回的所有响应(由一个开发为目的的同步请求的服务器的日期/时间)。
我目前正在努力寻找如何,在一个地方(通过在Global.asax或其他中央位置),我可以得到一个自定义标题,出现所有响应一个明显的例子。
答所接受,这是我的过滤器(pretty差不多),我加入的WebAPI配置的寄存器功能。
行注意:一个DateTime东西NodaTime,没有真正的理由只是有兴趣看它
公共覆盖无效OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Content.Headers.Add(ServerTime,Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime())的ToString());
}
配置行:
config.Filters.Add(新ServerTimeHeaderFilter());
对于您可以使用自定义ActionFilter( System.Web.Http.Filters
)
公共类AddCustomHeaderFilter:ActionFilterAttribute
{
公共覆盖无效OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Headers.Add(customHeader,自定义值日期和时间);
}
}
然后,您可以通过在Global.asax中添加该配置中,例如应用过滤器到控制器的所有操作:
GlobalConfiguration.Configuration.Filters.Add(新AddCustomHeaderFilter());
您还可以在筛选器属性应用到你想不全局cofiguration线的动作。
Simple question, and i am sure has a simple answer but i can't find it.
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).
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.
Answer accepted, here is my filter (pretty much the same) and the line i added to the Register function of the WebApi config.
NOTE: The DateTime stuff is NodaTime, no real reason just was interested in looking at it.
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Content.Headers.Add("ServerTime", Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()).ToString());
}
Config Line:
config.Filters.Add(new ServerTimeHeaderFilter());
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");
}
}
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.
这篇关于添加自定义标题,将网页API的所有响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!