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

Well, even though you are explicitly casting, Response.StatusCode is a child element of Response.

In most cases, the easiest way I find and following "best practices" for creating WebAPI's:

First, your method signature would change from:

public JsonResult Action() { ... }

to

public IHttpActionResult Action { ... }

then instead of returning Json() you would use the following:

return Content(HttpStatusCode.BadRequest, new {success = false, errors = errors }, Configuration.Formatters.JsonFormatter);

where the final variable, Configuration.Formatters.JsonFormatter is optional--remember, Json is the default return type (or ASP.NET allows for content negotiation and will follow what the client requests).

Hope that helps.


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.