Return a specific HTTP status code in action for a GET request

I am creating a REST service using the ASP.NET Web API. How can I return a 401 status code from an action for a GET method ...

I have no problem returning some status code, for example. POST because 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 the GET method when the method returns a 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, for example. 401 when authorization in this Get method failed

thanks

+2
source share
1 answer

You should throw an HttpResponseException , which allows you to specify a response code, for example:

 if (authFailed) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } 
+5
source

Source: https://habr.com/ru/post/1411535/


All Articles