I would like to have my Controllers return a HttpResponseMessage of 204 (NoContent), when i.e. the selected resource is not found.
Usually I code it like this:
public Contracts.IRoom Get(HttpRequestMessage request, int id)
{
return _RoomRepo.GetAllRooms().Where(r => r.Id == id).FirstOrDefault();
}
But this gives me a ResponseCode of 200 (Ok) and Data of null
So to achieve, what i am looking for, i have to code:
public HttpResponseMessage Get(HttpRequestMessage request, int id)
{
var room = _RoomRepo.GetAllRooms().Where(r => r.Id == id).FirstOrDefault();
if (room != null)
return request.CreateResponse(System.Net.HttpStatusCode.OK, room);
else
return request.CreateResponse(System.Net.HttpStatusCode.NoContent, room);
}
Is there an easier way of doing this? It seems like the asp.net guys might have already fixed this in MVC 6, as stated in ASP.Net Docs
Web API engine doesn't create all types of responses by itself. In your case, it doesn't know the meaning of 'null', and even if you have multiple statements interacting with database, a few of them returning null and other returning some data. So there is no way for API to detect 'NoContent' in this case.
Actually you have to create response type by your own for the users who are consuming your api in a simple understandable way.
You are doing best, as it is the exact role of controller class.
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