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);
    }
}

在这里,我还想设置一些标头值,但尽管它出现在请求中,但响应中不包含它。

有没有办法做到这一点?

4

2 回答 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);
        }
    }
于 2018-05-08T10:30:43.797 回答
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

于 2015-07-27T13:55:06.220 回答