c# - ASP.Net WebApi Controller 应该返回 204 而不是 null [HttpResponseMessage]

标签 c# asp.net asp.net-mvc asp.net-web-api

我想让我的 Controller 返回 204 (NoContent) 的 HttpResponseMessage,即找不到所选资源时。

通常我这样编码:

public Contracts.IRoom Get(HttpRequestMessage request, int id)
        {
            return _RoomRepo.GetAllRooms().Where(r => r.Id == id).FirstOrDefault();            
        }

但这给了我一个 200 的 ResponseCode (Ok) 和 null

的数据

因此,为了实现我正在寻找的目标,我必须编写代码:

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);
}

有更简单的方法吗? 正如 ASP.Net Docs 中所述,asp.net 人员似乎已经在 MVC 6 中修复了此问题

最佳答案

Web API 引擎不会自行创建所有类型的响应。在您的情况下,它不知道“null”的含义,即使您有多个语句与数据库交互,其中一些语句返回 null 而其他语句返回一些数据。因此,在这种情况下,API 无法检测到“NoContent”。

实际上,您必须以简单易懂的方式为使用您的 api 的用户创建自己的响应类型。

你做得最好,因为它是 Controller 类的确切角色。

关于c# - ASP.Net WebApi Controller 应该返回 204 而不是 null [HttpResponseMessage],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32251621/

相关文章:

c# - ASP.NET GridView自定义分页最后一页问题

c# - 货到付款插件在 NopCommerce 的付款方式页面中不可用

c# - 如何在 EF 中更新父实体时添加/更新子实体

c# - LINQ "queries"是否被编译成实际的 SQL 存储过程?

C# SameSite 标志问题

c# - 无法连接到任何指定的 MySQL 主机。 <添加名称 ="MySqlSiteMapProvider"

C# OpenGL字体显示

如果记录也存在,Javascript 无法按函数预期工作

asp.net - Json.Net 反序列化 - Web API 和可空日期

asp.net - 更新命令在动态数据详细信息 View 中不起作用