Add custom header to all responses in Web API

后端 未结 8 1141
我寻月下人不归
我寻月下人不归 2020-12-07 18:30

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

8条回答
  •  长情又很酷
    2020-12-07 19:15

    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.

提交回复
热议问题