我已经为我的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());
}
}
但是,当发生异常时,客户端会收到:
答案 0 :(得分:1)
您需要使用异常过滤器的响应抛出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的详细信息。
答案 1 :(得分:1)
您的API端代码没问题。但获得响应应该是这样的(使用WebException捕获):
oForm.elements[index of element].value;