如何在ASP.NET MVC中以JSON格式返回500错误?

11 asp.net-mvc jquery json

当ASP.NET MVC抛出异常时,它会返回500错误的响应类型text/html- 当然,这是无效的JSON.

我想响应一个Ajax请求,期望JSON出现我可以接收并显示给用户的错误.

  1. 是否可以返回HTTP状态代码为500的JSON?

  2. 当问题是缺少参数时,在控制器被调用之前会发生500错误 - 因此控制器解决方案可能无法正常工作.例如,在对通常返回JsonResult的Action的调用中保留必需的参数,ASP.NET MVC将其发送回客户端:

'/'应用程序中的服务器错误.参数字典包含方法'System.Web.Mvc.JsonResult EditUser(Int32,System.String,System.String,System.String,System)的非可空类型'System.Int32'的参数'id'的空条目. String,System.String,System.String,System.String,System.String)'in'bhh'.可选参数必须是引用类型,可空类型,或者声明为可选参数.参数名称:参数

我正在使用jQuery; 有没有更好的方法来处理这个?

Dar*_*rov 10

您可以使用自定义错误处理程序筛选器:

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new { errorMessage = "some error message" }
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后装饰您通过Ajax调用的控制器/操作,甚至注册为全局过滤器.

然后在执行Ajax请求时,您可以测试error属性的存在:

$.getJSON('/foo', function(result) {
    if (result.errorMessage) {
        // Something went wrong on the server
    } else {
        // Process as normally
    }
});
Run Code Online (Sandbox Code Playgroud)