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.

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

  • 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
        }
    });
    
    链接地址: http://www.djcxy.com/p/39204.html

    上一篇: 如何使用不同类型的ASP.NET MVC访问View中的字段

    下一篇: 我怎样才能在ASP.NET MVC的JSON格式返回500错误?