c# - Asp Core 3 - 如何在 Controller 方法中允许可为空的 [FromBody] 对象

标签 c# asp.net-core .net-core asp.net-core-3.1

假设我有一个带有一个 POST 方法的简单 Controller ,该方法从其主体中接受一个对象。但是,该对象在 HTTP 请求正文中的存在应该是可选的。我尝试使用以下代码实现此行为

public class User
{
    public string Name { get; set; }
}

[ApiController]
[Route("[controller]")]
public class GreetingController : ControllerBase
{
    [HttpPost]
    public string SayHello([FromBody] User user = null)
    {
        return "Hello " + user?.Name;
    }
}

如果我使用主体中的对象发出请求,则一切正常。但是使用这种配置,它无法发出空正文的 POST 请求。如果我创建一个没有 Content-Type 的请求标题(因为实际上没有内容),我收到以下错误:
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
    "title": "Unsupported Media Type",
    "status": 415,
    "traceId": "|192e45d5-4bc216316f8d3966."
}

如果Content-Type header 有值 application/json然后响应如下所示:
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|192e45d6-4bc216316f8d3966.",
    "errors": {
        "": [
            "A non-empty request body is required."
        ]
    }
}

那么,如何让请求体中的对象成为可选的呢?这是一个很常见的问题,我很好奇在 ASP Core 3 中是否有一个简单的解决方案。我不想从请求流中读取对象并自己反序列化它。

最佳答案

目前,唯一的方法是通过全局选项,MvcOptions.AllowEmptyInputInBodyModelBinding .默认为 false ,所以你只需要做:

services.AddControllers(o =>
{
    o.AllowEmptyInputInBodyModelBinding = true;
});

关于c# - Asp Core 3 - 如何在 Controller 方法中允许可为空的 [FromBody] 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61387180/

相关文章:

c# - 格式化数据网格中的值

c# - PNG CRC 是如何精确计算的?

asp.net-core - 使用 ConfigurationBuilder 检索 Web 应用程序连接字符串

c# - 在不同设备上运行时,TcpListener 不接受 TcpClient [C#、Unity]

c# - 有什么办法可以在下游类中读取 Serilog 的 LogContext?

c# - 使用 .netcore 3.0 和使用/p :PublishSingleFile=true flag? 时如何获取可执行文件的实际路径

c# - 数据绑定(bind)下拉列表与数据表并添加自定义值

c# - 如何以编程方式从共享点站点下载文件?

c# - 通过依赖注入(inject)获取连接字符串

c# - 无法从单例 'MyDbContext' 使用范围服务 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'