Add custom header to all responses in Web API

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

    I combined the normal and exception path in one class:

    public class CustomHeaderAttribute : FilterAttribute, IActionFilter, IExceptionFilter
    {
        private static string HEADER_KEY   { get { return "X-CustomHeader"; } }
        private static string HEADER_VALUE { get { return "Custom header value"; } }
    
        public Task ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func> continuation)
        {
            return (new CustomHeaderAction() as IActionFilter).ExecuteActionFilterAsync(actionContext, cancellationToken, continuation);
        }
    
        public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            return (new CustomHeaderException() as IExceptionFilter).ExecuteExceptionFilterAsync(actionExecutedContext, cancellationToken);
        }
    
        private class CustomHeaderAction: ActionFilterAttribute
        {
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Response != null)
                { 
                    actionExecutedContext.Response.Content.Headers.Add(HEADER_KEY, HEADER_VALUE);
                }
            }
        }
    
        private class CustomHeaderException : ExceptionFilterAttribute
        {
            public override void OnException(HttpActionExecutedContext context)
            {
                if (context.Response == null)
                {
                    context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception);
                }
    
                context.Response.Content.Headers.Add(HEADER_KEY, HEADER_VALUE);
            }
        }
    }
    

    Nothing fancy but at least it gives me one place to control my additional headers. For now it's just static content but you could always hook it up to some sort of dictionary generator/factory.

提交回复
热议问题