我已经为我的 Web API Controller 操作创建了一个异常过滤器,但它似乎没有做任何事情(即使它确实被调用)。
属性
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"
});
}
Controller
[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 的更多详细信息.
关于c# - 客户端没有收到来自 ApiController 的自定义 HttpResponseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31448620/