Why should I use IHttpActionResult instead of HttpResponseMessage?
asp.net-web-api, c#, httpresponse
Solution
You might decide not to use `IHttpActionResult` because your existing code builds a `HttpResponseMessage` that doesn't fit one of the canned responses. You can however adapt `HttpResponseMessage` to `IHttpActionResult` using the canned response of `ResponseMessage`. It took me a while to figure this out, so I wanted to post it showing that you don't necesarily have to choose one or the other:
public IHttpActionResult SomeAction()
{
IHttpActionResult response;
//we want a 303 with the ability to set location
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
responseMsg.Headers.Location = new Uri("http://customLocation.blah");
response = ResponseMessage(responseMsg);
return response;
}
Note, `ResponseMessage` is a method of the base class `ApiController` that your controller should inherit from.
Problem
I have been developing with WebApi and have moved on to WebApi2 where Microsoft has introduced a new `IHttpActionResult` Interface that seems to recommended to be used over returning a `HttpResponseMessage`. I am confused on the advantages of this new Interface. It seems to mainly just provide a SLIGHTLY easier way to create a `HttpResponseMessage`. I would make the argument that this is "abstraction for the sake of abstraction". Am I missing something? What is the real world advantages I get from using this new Interface besides maybe saving a line of code? Old way (WebApi): ``` public HttpResponseMessage Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { return new HttpResponseMessage(HttpStatusCode.OK); } else { throw new HttpResponseException(HttpStatusCode.NotFound); } } ``` New Way (WebApi2): ``` public IHttpActionResult Delete(int id) { var status = _Repository.DeleteCustomer(id); if (status) { //return new HttpResponseMessage(HttpStatusCode.OK); return Ok(); } else { //throw new HttpResponseException(HttpStatusCode.NotFound); return NotFound(); } } ```