开发者

How can I return 500 error in JSON format in ASP.NET MVC?

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

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

  1. Is it possible 开发者_如何学JAVAto return JSON with an HTTP status code of 500?

  2. 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:

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

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

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

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
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜