I'm creating REST service using ASP.NET Web API. How can I return 401 status code from action for GET method...
I don't have problem with returning some status code from e.g. POST method, cause I can set the return type to HttpResponseMessage
public HttpResponseMessage Post(Car car)
{
using (var context = new CarEntities())
{
...
var response = new HttpResponseMessage(HttpStatusCode.Created);
response.Headers.Location = new Uri(Request.RequestUri, path);
return response;
}
}
However, how can I return the status code for GET method, when the method returns different type than HttpResponseMessage:
public Car Get(int id)
{
var context = new CarEntities();
return context.Cars.Where(p => p.id == id).FirstOrDefault();
}
I would like to return e.g. 401 when authorization in this Get method failed
Thanks
You should throw a
HttpResponseException
, which allows you to specify the response code, for example: