客户端没有收到来自 ApiController 的自定义 HttpResponseException

Nic*_*las 5 .net c# asp.net-mvc asp.net-web-api

我已经为我的 Web API 控制器操作创建了一个异常过滤器,但它似乎没有执行任何操作(即使它确实被调用)。

属性

public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
        context.Response.Content = new StringContent("My content");
        context.Response.ReasonPhrase = "My reason";
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

public override void OnException(HttpActionExecutedContext context)
{
    throw new HttpResponseException(
        new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("The content"),
            ReasonPhrase = "The reason"
        });
}
Run Code Online (Sandbox Code Playgroud)

控制器

[ExceptionHandler]
public class MyController : ApiController
{
    [Route("MyRoute"), HttpGet]
    public MyModel Index() {
        // code causing exception
    }
}
Run Code Online (Sandbox Code Playgroud)

WebApi配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ExceptionHandlerAttribute());
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当发生异常时,客户端会收到以下消息:

异常信息

Enr*_*lio 2

您需要抛出HttpResponseException异常过滤器的响应:

public override void OnException(HttpActionExecutedContext context)
{
    throw new HttpResponseException(
        new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("The content"),
            ReasonPhrase = "The reason"
        });
}
Run Code Online (Sandbox Code Playgroud)

以下是有关如何处理 Web API 中的异常的更多详细信息。