I am attempting to write truly RESTful web services over HTTP using ASP.NET MVC 4 Web API.
The current challenge I have is to return different return types (entity-body)
I derived the clean answer to this question from an answer I received on this other question.
If I make my return value HttpResponseMessage
, I can return whatever status or content I need to by returning either a new HttpResponseMessage()
.
EDIT 5/10/2012: Thanks to input from @DarrelMiller, removed deprecated HttpResponseMessage<T>
and replaced with call to HttpRequestMessage.CreateResponse<T>()
extension method. NOTE: This extension method is not available in the MVC4/WebAPI beta. You need to build from source or get the nightly build.
Oversimplified example:
public HttpResponseMessage Post(MyResource myResource)
{
...
if (goodStuff)
{
return ControllerContext.Request.CreateResponse(HttpStatusCode.Created, myNewResource);
}
else if (badStuff)
{
return ControllerContext.Request.CreateResponse(HttpStatusCode.BadRequest, badRequest);
}
else
{
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}