代码之家  ›  专栏  ›  技术社区  ›  Kevin Smith

如何在asp.net core 3.1中向终结点传递正文中的空值

  •  0
  • Kevin Smith  · 技术社区  · 5 年前

    我在asp.net Core3.1控制器中有以下操作

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

    1 , 2

    但是,我找不到办法 null 传入的值。

    如果我经过一具空尸体或 无效的 body I获取状态代码400,返回验证消息 A non-empty request body is required.

    我也试着改变 value 参数为可选参数,默认值为 无效的 :

    public async Task<IActionResult> Post(string id, [FromBody] int? value = null)
    

    如何将空值传递给此操作?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Nkosi    5 年前

    参考 Automatic HTTP 400 responses

    这个 [ApiController] 属性使模型验证错误自动触发HTTP 400响应

    移除 [顶点控制器] 以允许无效请求仍对控制器操作执行,并且如果具有该属性的附加功能对当前控制器不重要。

    但是,需要手动应用所需的功能

    [Route("example")]
    public class MyExampleController : ControllerBase {
        [HttpPost("{id}/value")]
        public async Task<IActionResult> Post(string id, [FromBody] int? value) {
    
            if (!ModelState.IsValid) {
    
                //...
    
                return BadRequest(ModelState);
            }
    
            //...
    
            return Ok();
        }
    }
    
        2
  •  1
  •   Kevin Smith    5 年前

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

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

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

    这样我们就可以进去了 null

    public async Task<IActionResult> Post(string id,
            [FromBody][Range(1, int.MaxValue, ErrorMessage = "Please enter a value bigger than 1")]
            int? value = null)
    
        3
  •  0
  •   Arthur Grigoryan    5 年前

    这似乎与通过JSON执行单个值的方式有关。它需要一个值,空值只是创建一个空的请求体。你应该考虑定义这样一个类

        public class MyInt{
            public int Value { get; set; }
            public bool IsNull { get; set; }
        }
    
        [ApiController]
        [Route("example")]
        public class MyExampleController : ControllerBase
        {
            [HttpPost("{id}/value")]
            public IActionResult Post(string id, [FromBody]MyInt value)
            {
                if(value.IsNull){
    
                }
                else{
    
                }
                return Ok();
            }
        }
    

    换句话说,当你发帖的时候,你不仅仅使用默认值。你可以这样做

    [HttpPost("{id}/value")]
    public IActionResult Post(string id, [FromBody]int value)...
    [HttpGet("{id}/value")]
    public IActionResult Get(string id)...//use the default value here