假设我有一个带有一个 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/