gpt4 book ai didi

c# - 如何将正文中的null传递给asp.net core 3.1中的终结点

转载 作者:行者123 更新时间:2023-12-03 21:47:12 25 4
gpt4 key购买 nike

我在asp.net core 3.1 Controller 中有以下操作

[ApiController]
[Route("example")]
public class MyExampleController : ControllerBase
{
[HttpPost("{id}/value")]
public async Task<IActionResult> Post(string id, [FromBody] int? value)
=> Task.FromResult(Ok());
}

如果我发布int的主体值(例如: 12等),则效果很好

但是,我找不到获取传入的 null值的方法。

如果我传入一个空的正文或 null正文,则会返回状态码400,并返回一个验证消息 A non-empty request body is required.

我还尝试将 value参数更改为默认参数 null的可选参数:
public async Task<IActionResult> Post(string id, [FromBody] int? value = null)

如何将null传递给此操作?

最佳答案

终于弄明白了,非常感谢@Nkosi和@KirkLarkin帮助错误找到了这个。

在将 Controller 配置到容器中时,在Startup.cs中,我们只需要将默认的mvc选项更改为AllowEmptyInputInBodyModelBinding

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(x => x.AllowEmptyInputInBodyModelBinding = true);
}

这样,我们可以将 null传递到帖子的正文中,并且效果很好。它还仍然通过属性应用普通模型验证,而无需手动检查ModelState:
public async Task<IActionResult> Post(string id,
[FromBody][Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 1")]
int? value = null)

关于c# - 如何将正文中的null传递给asp.net core 3.1中的终结点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59812908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com