MVC 3 + REST return custom HTTP error?

In my application I am trying to get it so that when the REST api call is made, if there is an error that it returns the correct status code, then either Json or Xml in the response body.

So 400: { 'ErrorCode': '400', 'Reason' : 'You did something wrong..' }

or 400: <Error><ErrorCode>400</ErrorCode><Reason>You did something wrong</Reason></Error>

However, I cannot find how to set the status and body to make this happen. With a fiddler check what is being passed back and fourth I found that if I return normal ActionResult

then I can return the body message ok but the state is 200. If I use HttpException

then I can set the status code but the body message returns as big html document. I tried using HttpStatusCodeResult

but it just seems to fail and returns 302.

I'm a little confused.


source to share

3 answers

Try it Response.StatusCode = (int)HttpStatusCode.BadRequest;

in your action method. Check out this article on develoq for a quick guide:



The Web API can handle this in a variety of ways, but if you want to stick with ASP.NET MVC use the following code:

 Response.StatusCode = 500;
 Response.TrySkipIisCustomErrors = true;
 return Content("Error description goes here.", "text/plain");




Check out the MVC 4 beta for a new feature called Web API to help you fix this issue.



All Articles