Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Mvc.JsonResult plus set Response.StatusCode

Project: ASP MVC 4 running under .net 4.0 framework:

When running an application under VS 2010 express (or deployed and running under IIS 7.5 on my local machine) the following (pseudocode) result from an action works as expected

[HttpPost] public ActionResult PostWord(Model model) {    ....    Response.StatusCode = 400;    Return new JsonResult { data = new {fieldName = "Word", error = "Not really a word!" } }; 

(and I have assigned ContentType and ContentEncoding properties of the JsonResult object, with no difference in behaviour)

When the deployable is moved onto a web host (using IIS 7), firebug is telling me that the response is as expected (400) but there is no JSON in the response (ie there is no text of any kind). If I remove the line

Response.StatusCode = 400; 

from the action, the JSON is perfectly formed in the response, but of course the response status code is 200 (OK), which interferes with the consuming javascript and appropriate function call.

Any thoughts on what might be going on and how to fix this? Thank you

like image 289
Brent Avatar asked Jun 19 '13 04:06

Brent


People also ask

What does JsonResult return?

JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

How do I return a JSON response in C#?

ContentType = "application/json; charset=utf-8"; Response. Write(myObjectJson ); Response. End(); So you return a json object serialized with all attributes of MyCustomObject.

How do I return JSON in Web API net core?

To return data in a specific format from a controller that inherits from the Controller base class, use the built-in helper method Json to return JSON and Content for plain text. Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult .


1 Answers

I had this exact same problem; in order to make sure that the correct answer is not buried in the comments (as it was for me), I want to reiterate @Sprockincat's comment:

For me at least, it was indeed an issue with IIS Custom errors, and can be solved with:

Response.TrySkipIisCustomErrors = true; 

@Sprockincat - you should get credit for this. I'm just making it more visible because it's such a subtle fix to a problem that is quite difficult to diagnose.

like image 90
Robert Avatar answered Oct 09 '22 00:10

Robert