简体   繁体   English

ASP.Net WebApi控制器应返回204而不是null [HttpResponseMessage]

[英]ASP.Net WebApi Controller should return 204 instead of null [HttpResponseMessage]

I would like to have my Controllers return a HttpResponseMessage of 204 (NoContent), when ie the selected resource is not found. 我希望我的控制器返回HttpResponseMessage为204(NoContent),即找不到所选资源。

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 但这给了我一个200的响应代码(Ok)和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 看起来asp.net的人可能已经在MVC 6中解决了这个问题,如ASP.Net Docs中所述

Web API engine doesn't create all types of responses by itself. Web API引擎本身不会创建所有类型的响应。 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. 在您的情况下,它不知道'null'的含义,即使您有多个与数据库交互的语句,其中一些返回null而其他返回一些数据。 So there is no way for API to detect 'NoContent' in this case. 因此,在这种情况下,API无法检测到“NoContent”。

Actually you have to create response type by your own for the users who are consuming your api in a simple understandable way. 实际上,您必须以简单易懂的方式为使用api的用户创建自己的响应类型。

You are doing best, as it is the exact role of controller class. 你做得最好,因为它是控制器类的确切角色。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM