我为我的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";
}
}
我也尝试过:
public override void OnException(HttpActionExecutedContext context)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The content"),
ReasonPhrase = "The reason"
});
}
调节器
[ExceptionHandler]
public class MyController : ApiController
{
[Route("MyRoute"), HttpGet]
public MyModel Index() {
// code causing exception
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ExceptionHandlerAttribute());
}
}
但是,当发生异常时,客户端会收到以下信息:
最佳答案 您需要使用异常过滤器的响应抛出HttpResponseException:
public override void OnException(HttpActionExecutedContext context)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The content"),
ReasonPhrase = "The reason"
});
}
这里有关于how to handle exceptions in Web API的更多细节.