Returning HttpResponseMessages from the ASP.Net webAPI

For consistency, I’ve adopted the following return codes, but I may alter these if there is some compelling reason or someone sheds some light on why these might not be the best options:

HTTPGet = Select (Success -> return the items, but don’t return a return message)
(Fail -> throw new HttpResponseException(HttpStatusCode.NotFound = 404 );)

HttpPost = Insert ( Success -> return HttpStatusCode.Created = 201)
( or Assumed Success -> HttpStatusCode.Accepted = 202 )

( Fail -> return HttpStatusCode.ExpectationFailed = 417)

HttpPut = Update ( Success -> HttpStatusCode.OK = 200)
( or Assumed Success -> HttpStatusCode.Accepted = 202 )

( Fail -> return HttpStatusCode.ExpectationFailed = 417)

HttpDelete ( Success -> HttpStatusCode.NoContent = 204)
( or Assumed Success -> HttpStatusCode.Accepted = 202 )

( HttpStatusCode.ExpectationFailed = 417)

HttpPatch ( Success -> HttpStatusCode.OK = 200)
( or Assumed Success -> HttpStatusCode.Accepted = 202 )

( Fail -> return HttpStatusCode.ExpectationFailed = 417)

Also, for HttpGets, I’m not returning the entire entity back, mainly because in my case I’m dealing with RPC type setup and I don’t have the full entity, but I’m often calling functions like ‘int CreateEntity()’ which will create an entity and simply return an id, so what I’m doing is putting the return value into the content of the HttpResponseMessage. The following function is an example:

[HttpPost]
public HttpResponseMessage CreateAnObject(string name )
{
int retVal = _equipService.CreateAnObject(name);
if (retVal > 0)
{
//succeeded
return ControllerContext.Request.CreateResponse<int>(HttpStatusCode.Created,retVal);
}
else
{
//failed
return ControllerContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s