Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API controlling success code (200 versus 201)

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;
}
like image 444
govin Avatar asked Oct 02 '22 20:10

govin


2 Answers

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.

like image 164
Kiran Avatar answered Oct 05 '22 10:10

Kiran


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.

like image 31
Tom Hall Avatar answered Oct 05 '22 09:10

Tom Hall