此问题的先前答案并未说明如果您的控制器操作引发异常该怎么办。有两种基本方法可以让它发挥作用:
添加异常过滤器:
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
public class HeaderAdderExceptionFilter : 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", "value");
}
}
在您的 WebApi 设置中:
configuration.Filters.Add(new HeaderAdderExceptionFilter());
这种方法有效,因为 WebApi 的默认异常处理程序将发送在过滤器中创建的 HttpResponseMessage,而不是构建自己的。
替换默认异常处理程序:
using System.Net;
using System.Net.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Results;
public class HeaderAdderExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
HttpResponseMessage response = context.Request.CreateErrorResponse(
HttpStatusCode.InternalServerError, context.Exception);
response.Headers.Add("header", "value");
context.Result = new ResponseMessageResult(response);
}
}
在您的 WebApi 设置中:
configuration.Services.Replace(typeof(IExceptionHandler), new HeaderAdderExceptionHandler());
您不能同时使用这两种方法。好吧,你可以,但是处理程序永远不会做任何事情,因为过滤器已经将异常转换为响应。
非常重要的是要注意如所写,此代码会将所有异常详细信息发送给客户端。您可能不想在生产环境中执行此操作,因此请检查 CreateErrorResponse() 上所有可用的重载,然后选择适合您需要的重载。