如何在ASP.NET MVC中以JSON格式返回500错误? [英] How can I return 500 error in JSON format in ASP.NET MVC?

查看:136
本文介绍了如何在ASP.NET MVC中以JSON格式返回500错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When ASP.NET MVC throws an exception, it returns a 500 error with response type text/html- which, of course, is invalid JSON.

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

I want to respond to an Ajax request expecting JSON with an error I can receive and display to the user.

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

  1. Is it possible to return JSON with an HTTP status code of 500?

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

When the problem is a missing parameter, the 500 error occurs before the controller is even called - so a controller solution might not work. For example, leaving a required parameter out in a call to an Action that normally returns a JsonResult, ASP.NET MVC sends this back to the client:

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

Server Error in '/' Application. The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult EditUser(Int32, System.String, System.String, System.String, System.String, System.String, System.String, System.String, System.String)' in 'bhh'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

我正在使用jQuery;有更好的方法来解决这个问题吗?

I'm using jQuery; is there a better way to handle this?

推荐答案

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

You could use a custom error handler filter:

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" }
            };
        }
    }
}

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

And then decorate your controller/actions that you are calling through Ajax or even register as global filter.

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

Then when performing the Ajax request you can test the presence of the error property:

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

这篇关于如何在ASP.NET MVC中以JSON格式返回500错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆