Add custom header to all responses in Web API

后端 未结 8 1097
我寻月下人不归
我寻月下人不归 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

    Julian's answer led me to have to create the filter but only using the the System.Web (v4) and System.Web.Http (v5) namespace (MVC packages were not part of this particular project this was used on.)

    using System.Web;
    using System.Web.Http.Filters;
    ...
    public class AddCustomHeaderActionFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
            actionExecutedContext.ActionContext.Response.Headers.Add("name", "value");
        }
    }
    

    And add it to the global.asax to have it used on every controller/action

            GlobalConfiguration.Configuration.Filters.Add(new AddCustomHeaderActionFilterAttribute());
    

提交回复
热议问题