Add custom header to all responses in Web API

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

    Neither of the above two solutions worked for me. They wouldn't even compile. Here's what I did. Added:

    filters.Add(new AddCustomHeaderFilter());
    

    to RegisterGlobalFilters(GlobalFilterCollection filters) method in FiltersConfig.cs and then added

    public class AddCustomHeaderFilter : ActionFilterAttribute
    {
       public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
       {
           actionExecutedContext.HttpContext.Response.Headers.Add("ServerTime", DateTime.Now.ToString());
       }
    }
    

提交回复
热议问题