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

时间:2015-07-27 12:26:56

标签: c# asp.net-web-api http-headers 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);
    }
}

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

有没有办法做到这一点?

2 个答案:

答案 0 :(得分: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...");
        }
    }

}

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

答案 1 :(得分:0)

有一个示例代码供您参考,我的ApiExceptionHandler是您的 FooExceptionHandler

    public class ApiExceptionHandler : ExceptionHandler
    {
        public override void Handle(ExceptionHandlerContext context)
        {
            var response = new Response<string>
            {
                Code = StatusCode.Exception,
                Message = $@"{context.Exception.Message},{context.Exception.StackTrace}"
            };

            context.Result = new CustomeErrorResult
            {
                Request = context.ExceptionContext.Request,
                Content = JsonConvert.SerializeObject(response),                
            };
        }
    }

    internal class CustomeErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response =
                new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(Content),
                    RequestMessage = Request
                };

            response.Headers.Add("Access-Control-Allow-Origin", "*");
            response.Headers.Add("Access-Control-Allow-Headers", "*");

            return Task.FromResult(response);
        }
    }
相关问题