简体   繁体   中英

Returning Status Code 400 Not Triggering Ajax OnFailure

I'm making an ajax post to an ASP.NET MVC action method and want to return an error as Json which should trigger the onFailure function. The code below works on my dev machine but as soon as I tried on our test environment the onFailure function is never hit.

I cannot use a solution that checks a boolean value in the onSuccess function to see whether a failure has occurred. I need a solution that will fire the onFailure function.

    public static ActionResult GetModelErrorsInJson(this Controller controller)
    {
        controller.Response.StatusCode = (int)HttpStatusCode.BadRequest;

        var errors = controller.ModelState.Values
            .SelectMany(x => x.Errors)
            .Select(x => x.ErrorMessage);

        var jsonErrors = JsonConvert.SerializeObject(errors);
        return new JsonResult()
        {
            Data = jsonErrors
        };
    }

Apparently IIS was messing with my response and breaking things. I fixed it by setting the following property on the response.

controller.Response.TrySkipIisCustomErrors = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM