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
Try it Response.StatusCode = (int)HttpStatusCode.BadRequest;
in your action method. Check out this article on develoq for a quick guide: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/
source to share