Is there a way to specify the success return code for a method in Web API controller?
My initial controller was structured like below
public HttpResponseMessage PostProduct(string id, Product product)
{
var product= service.CreateProduct(product);
return Request.CreateResponse(HttpStatusCode.Created, product);
}
However, there is drawback to the above approach when you generate Web API help pages. The Web API Help page API cannot automatically decode that the strongly typed Product is the response and hence generate a sample response object in its documentation.
So I go with the below approach, but here the success code is OK (200)
and not Created (201)
. Anyway I can control the success code of the method using some attribute style syntax? Plus, I would also like to set the Location header to the URL where the created resource is available - again, this was easy to do when I was dealing with HttpResponseMesage
.
public Product PostProduct(string id, Product product)
{
var product= service.CreateProduct(product);
return product;
}
Regarding your observation below:
However, there is drawback to the above approach when you generate Web API help pages. The Web API Help page API cannot automatically decode that the strongly typed Product is the response and hence generate a sample response object in its documentation.
You can take a look at HelpPageConfig.cs
file that gets installed with HelpPage package. It has an example exactly for a scenario like yours where you can set the actual type of the response.
In latest version (5.0 - currently RC) of Web API we have introduced an attribute called ResponseType
which you can use to decorate the action with the actual type. You would be able to use this attribute for your scenario.
I do this:
[HttpGet]
public MyObject MyMethod()
{
try
{
return mysService.GetMyObject()
}
catch (SomeException)
{
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content =
new StringContent("Something went wrong.")
});
}
}
If you don't get what you expected, throw a HttpResponseException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With