调用Controller.OnException,但仅在生产环境中返回错误500,

时间:2019-02-21 20:59:30

标签: asp.net-mvc exception http-error

我的Asp.Net MVC应用程序中有一个奇怪的行为。我已经在控制器中重写了OnException方法来处理错误:

protected override void OnException(ExceptionContext filterContext)
{
    var action = filterContext.RouteData.Values["action"].ToString();
    var type = filterContext.Controller.GetType();
    var httpMethod = filterContext.RequestContext.HttpContext.Request.HttpMethod;
    filterContext.ExceptionHandled = true;

    var returnType = GetReturnType(type, action, httpMethod);
    if (returnType == typeof(JsonResult))
        filterContext.Result = HandleJsonError(filterContext.Exception);
    else
        filterContext.Result = HandleError(filterContext.Exception);
}

上面的代码标识所调用的方法是普通视图结果还是jsonResult,并显示错误页面或在json中返回错误消息。如果是Json,则返回类似这样的内容:

{"OK":false,"ErrorMessage":"Error message to the user"}

因此,当发生错误时,浏览器会收到HTTP 200代码,就像没有错误一样,但是在我的客户端代码中,我识别了错误消息并将其显示给用户。

这在我的开发环境上运行良好,但是当我将其上传到生产环境时,异步请求返回了HTTP 500错误,但是返回的内容仍然是相同的JSON。这意味着OnException仍被调用,但是返回的是500而不是200的代码。如何在生产环境中将其重新返回200?

0 个答案:

没有答案
相关问题