Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server not returning JSON with status code 400 (.net)

I've got a weird problem with returning a 400 status code with json on error.

In my controller, I've got something like:

if(!ModelState.IsValid)
{
    string[] errors = ModelState.Values
                            .SelectMany(x => x.Errors)
                            .Select(x => x.ErrorMessage).ToArray<string>();

    Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
    return Json(new { success = false, errors = errors }, JsonRequestBehavior.DenyGet);
}

This works fine on my development machine. I can get the errors in the ajax error method. But when I deploy to the server, the server doesn't return the JSON anymore. I always get responseText instead of reponseJSON. If I remove the Response.StatusCode it works fine.

This leads me to believe that the function 'returns' when I set the Response object's StatusCode property. Has this happened to anyone else? Anyone know the solution?

like image 982
reggaemahn Avatar asked May 19 '16 03:05

reggaemahn


1 Answers

I finally figured out what the problem is. Posting this here as an answer for anyone else who may be pulling their hair out over this.

Set the following:

Response.TrySkipIisCustomErrors = true;

Make sure that this is set before you set the status code. I also figured out why it was working on my local machine and not on the test/uat servers. In my web.config, the CustomErrors was set to Off whereas on the servers it was set to On.

Seems like the server 'returns' as soon as it sees a BadRequest status code being written to the Response.

like image 166
reggaemahn Avatar answered Oct 19 '22 23:10

reggaemahn