3

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

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

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

However I can't seem to find how to set the status and body to make this happen. Using fiddler inspect whats being passed back and fourth I've found that if I return a normal ActionResult then I can return the body message ok but the status is 200. If I use HttpException then I can set the status code but the body message is returned as a large html document. I've tried using HttpStatusCodeResult but that just seems to fail and return a 302.

I'm a bit stumped.

1
  • Pretty sure thrown exceptions are passed back over Rest. Unless you have it disabled somewhere Commented Mar 9, 2012 at 15:01

3 Answers 3

2

Try Response.StatusCode = (int)HttpStatusCode.BadRequest; in your action method. Check out this article at develoq for a short tutorial: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/

Sign up to request clarification or add additional context in comments.

Comments

2

Web API can handle this in various ways, but if you want to stick to ASP.NET MVC then use the code below:

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

Comments

1

Check out MVC 4 Beta, there is a new feature called Web API that will help you solve this issue.

3 Comments

Can't use MVC 4 until it goes alpha I'm afraid.
@David I dont know if its the solution. But MVC 4 is is beta. asp.net/mvc/mvc4
@Doomsknight yes apologies, I meant until it gets its official release date. Don't know why I wrote alpha :s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.