Web API全局错误处理在响应中添加自定义标头

Dr *_*izo 5 c# http-headers asp.net-web-api exceptionhandler

我想知道是否有可能在发生内部服务器错误时设置一些自定义标头值?我目前在做:

public class FooExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        // context.Result already contains my custom header values
        context.Result = new InternalServerErrorResult(context.Request);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我还想设置一些标头值,但是虽然它出现在请求中,但响应不包含它.

有办法做到这一点吗?

Per*_*ddy 0

通过创建您自己的异常过滤器应该可以实现。

namespace MyApplication.Filters
{
    using System;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http.Filters;

    public class CustomHeadersFilterAttribute : ExceptionFilterAttribute 
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            context.Response.Content.Headers.Add("X-CustomHeader", "whatever...");
        }
    }
Run Code Online (Sandbox Code Playgroud)

}

http://www.asp.net/web-api/overview/error-handling/exception-handling