Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning http status code from Web Api controller

I'm trying to return a status code of 304 not modified for a GET method in a web api controller.

The only way I succeeded was something like this:

public class TryController : ApiController {     public User GetUser(int userId, DateTime lastModifiedAtClient)     {         var user = new DataEntities().Users.First(p => p.Id == userId);         if (user.LastModified <= lastModifiedAtClient)         {              throw new HttpResponseException(HttpStatusCode.NotModified);         }         return user;     } } 

The problem here is that it's not an exception, It's just not modified so the client cache is OK. I also want the return type to be a User (as all the web api examples shows with GET) not return HttpResponseMessage or something like this.

like image 903
ozba Avatar asked May 18 '12 15:05

ozba


People also ask

How do I retrieve my HTTP status code?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error. Copied!

How do I return HTTP response messages in Web API?

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response. Convert directly to an HTTP response message. Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Write the serialized return value into the response body; return 200 (OK).


1 Answers

I did not know the answer so asked the ASP.NET team here.

So the trick is to change the signature to HttpResponseMessage and use Request.CreateResponse.

[ResponseType(typeof(User))] public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient) {     var user = new DataEntities().Users.First(p => p.Id == userId);     if (user.LastModified <= lastModifiedAtClient)     {          return new HttpResponseMessage(HttpStatusCode.NotModified);     }     return request.CreateResponse(HttpStatusCode.OK, user); } 
like image 106
Aliostad Avatar answered Oct 12 '22 22:10

Aliostad