Home > Net >  ASP.NET MVC controller return JSON on error. Not consistent on dev machine vs. dev server
ASP.NET MVC controller return JSON on error. Not consistent on dev machine vs. dev server

Time:02-05

I have a MVC controller returning Task in a FileUpload function. (I use a Controller in stead of ApiController to make the file upload work properly)

My problem is whenever an exception is thown (for instance a file not being on a white list of allowed file types), my code behaves differently when debugging compared to code on a dev server I have.

My code:

//Exception is thown, message is put into the errorMessage parameter
Response.StatusCode = 500;
Response.StatusDescription = errorMessage;
Response.ContentType = "application/json";
return Json(new { Type = "Error", Message = errorMessage });

On the dev server, I get HTML result enter image description here

I can't find any significant differences in web.configs Does anyone know where to investigate ? This might be a simple configuration thing, but I can't figure this out.

CodePudding user response:

The IIS custom errors are intercepting the response and replacing it with an error page. Either setting Response.TrySkipIisCustomErrors = true; or changing the httpErrors[existingResponse] setting to PassThrough should allow the original response to be returned.

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>
  •  Tags:  
  • Related