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

6
我想知道是否有可能在发生内部服务器错误时设置一些自定义的标题值?我目前正在执行以下操作:
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个回答

2

这是一个示例代码,我的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);
        }
    }

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


我曾希望可以通过异常处理器来实现这一点, 然而经过进一步的调查和反编译, 我发现标题被剥离到了最基本的状态。我认为使用过滤器是唯一的方法,或者通过DelegatingHandler。 - Dr Schizo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接