ASP.NET Web API ExceptionHandler无法处理JavaScript XmlHttpRequest

时间:2018-07-23 09:25:55

标签: javascript c# asp.net asp.net-mvc asp.net-web-api

我有一个异常处理程序,

public class MyExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var content = new { message = context.Exception.Message };

        var jsonContent = JsonConvert.SerializeObject(content, Formatting.Indented);

        var httpResponseMessage = new HttpResponseMessage
        {
            Content = new StringContent(jsonContent, Encoding.UTF8, "application/json")
        };

        switch (context.Exception)
        {
            case InvalidServiceRequestException _:
                httpResponseMessage.StatusCode = HttpStatusCode.BadRequest;
                break;
            case EntityNotFoundException _:
                httpResponseMessage.StatusCode = HttpStatusCode.NotFound;
                break;                
            default:
                httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
                break;
        }

        context.Result = new MyActionResult(httpResponseMessage);
    }
}

然后在管道中设置此处理程序,

private static void ConfigureErrorHandler(HttpConfiguration config)
{
        config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());
}
  • 当我使用Postman向操作发送请求时,例外 处理。
  • 但是当我使用ajax(XmlHttpRequest)发送请求时,异常处理程序不会处理任何事情。

我这样设置cors:

private static void ConfigureCors(HttpConfiguration config)
{
        var corsAttribute = new EnableCorsAttribute("http://127.0.0.1:14725", "*", "*");
        config.EnableCors(corsAttribute);
}

这是什么问题?

0 个答案:

没有答案