How to return JSON object when Bad Request MVC

I am working on an MVC 4 project.

I have an action to execute when executing an Ajax Post request.

In some case that I could pinpoint, I need to set the Status property of the Response object to HttpBadRequest , and return a JSON object that contains some data that will be displayed to the end user.

the problem is that I cannot get the JSON object in the javascript method, I get something else. and this is because I set the Status property for the Response parameter for HttpBadRequest.

Here is the detailed information

Act

 // this method will executed when some Ajax Post request. [HttpPost] public ActionResult Delete(int id) { // some code here ...... // in some case we will determine an error like this if(error) { HttpContext.Response.Clear(); HttpContext.Response.TrySkipIisCustomErrors = true; HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { Message = string.Format(format, values), Status = messageType.ToString() }); } } 

and I want to read this returned JSON object from a javascript function like this

Javascript

 function OnDeleteFailed(data) { debugger; var try1 = $.parseJSON(data.responseText); var try2 = JSON.parse(data.responseJSON); } 

the problem is that the JSON object will NOT be populated in the javascript data variable. when debugging Javascirpt code, I get the following in the data variable

enter image description here

The strangest thing is that when I delete this line from Action

 HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; 

then I got the JSON object correctly and I could read it as

enter image description here

Note. I get the correct JSON object, but in a different Javascript function. (Now I get the JSON object in the OnDeleteSuccess function, and not in the OnDeleteFailed function.

So, Question : what is wrong with the code, so the JSON object will not be received in the javascript function if I set the "StatusCode" property of the "Answer" object to the "BadRequest" value?

I searched a lot for an answer (from yesterday), and after a long search this is the most urgent question for me, but, unfortunately, the solution to this question did not work for me at all.

Update

here is a fragment of the Web.config file that installs some of the IIS httpErros . This is an update to answer the assumption that the cause of the error will come from this point.

 <system.webServer> <httpErrors errorMode="Custom" existingResponse="Replace"> <remove statusCode="404" /> <error statusCode="404" responseMode="ExecuteURL" path="/Home/PageNotFound" /> </httpErrors> </system.webServer> 

Any ideas would be appreciated.

+6
source share
1 answer

In Web.Config , try changing the existingResponse to Auto :

 <httpErrors errorMode="Custom" existingResponse="Auto"> 

See Documentation

+2
source

All Articles