Reputation: 5929
I have the below example code which works in my local development environment but when publishing to a live environment which uses HTTPS and uses the .NET bundling for the javascript, and ELMAH for error logging, this no longer works as intended.
Instead of a JSON content response I get a HTML content response with the responseText
"Bad Request" and no responseJSON
property so this code results in a javascript error.
Does anyone know why the content type would get changed? presumably due to this being in a live environment and a response code of 400? but I'm not sure what is going on here.
Controller:
public JsonResult JsonModelErrorResult()
{
Response.StatusCode = 400;
var errors = ModelState.Values.SelectMany(m => m.Errors);
return Json(errors);
}
[HttpPost]
public ActionResult GetData()
{
...
if (results != null && results.Any())
{
return Json(result, JsonRequestBehavior.AllowGet);
}
else
{
ModelState.AddModelError("SearchResults", "No results found");
return this.JsonModelErrorResult();
}
}
Javascript:
$.ajax("/Controller/GetData/", {
dataType: "json",
type: "POST",
contentType: "application/json"
})
.done((result) => {
})
.fail((xhr) => {
setTimeout(() => {
this.errors(xhr.responseJSON);
}, 200);
})
.always(() => {
});
Update:
This is the response header when I view the response for the request in Chrome:
HTTP/1.1 400 Bad Request
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: text/html
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Thu, 03 Jul 2014 12:08:23 GMT
Content-Length: 11
and the returned value from the ajax call is a Jquery jqXHR object with a responseText
property of "Bad Request"
and a content type of "text/html"
UPDATE 2: This is the custom errors setup in my web.config
<customErrors mode="RemoteOnly" defaultRedirect="~/Error">
<error statusCode="401" redirect="~/Error/NotAuthorised" />
<error statusCode="403" redirect="~/Error/NotAuthorised" />
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
When testing I changed the mode to "Off" but this did not work in the live environment which is IIS8, maybe I missed something that need to be updated in order for IIS to do this correctly or that the defaultRedirect="~/Error">
should have also been removed?
but adding the line
Response.TrySkipIisCustomErrors = true;
into the JsonModelErrorResult code has stopped this content/html error with the line "Bad Request" being returned.
Upvotes: 0
Views: 1904
Reputation: 25521
Right after you set the Response.StatusCode
add this line of code:
Response.TrySkipIisCustomErrors = true;
This tells IIS not to intercept the request and use its own error page.
Upvotes: 6