Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c# - 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.

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...