ASP.NET core - 如何传递可选的 [FromBody] 参数?

Paw*_*wel 15 c# controller asp.net-core

如何在 ASP.NET Core (5.0) 中传递可选(可为空)[FromBody] 参数?如果我不在请求中发送正文,则会收到 415 不支持的媒体类型错误。可以配置吗?如果可以,如何在控制器或操作而不是应用程序级别上进行配置?我认为它必须与模型验证有关,但不确定。谢谢。

[HttpGet("[action]")]
public async Task<IActionResult> GetElementsAsync([FromBody] IEnumerable<int> elements = default)
{
  var result = await dataService.GetData(elements);
  return Ok(result);
}
Run Code Online (Sandbox Code Playgroud)

编辑:澄清一下:

这是典型的场景并且可以正常工作: 这是典型场景并且可以正常工作

但是传递空主体会立即返回 415,甚至没有到达行动: 传空体就是没有到达action就立即返回415

Nic*_*ada 12

您可以在这里找到解决方案:
https ://github.com/pranavkm/OptionalBodyBinding

来自github上的这个问题:
https ://github.com/dotnet/aspnetcore/issues/6878

从 .net Core 5 开始,您可以使用这个:

public async Task<IActionResult> GetElementsAsync([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] IEnumerable<int> elements = default)
...
Run Code Online (Sandbox Code Playgroud)

还需要(来自 Pawel 的经验):

services.AddControllers(options =>{options.AllowEmptyInputInBodyModelBinding = true;})
Run Code Online (Sandbox Code Playgroud)


Tin*_*ang 11

只需在请求标头中添加内容类型即可。当身体空的时候,没有意志content-type:application/json就会出现。415

您的控制器没有任何变化。在我这边测试是没问题的。

在此输入图像描述

我创建了一个新的 asp.net core 5 api 项目,这是我的控制器:

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace WebApi_net5.Controllers
{
    public class HomeController : ControllerBase
    {
        [HttpGet("[action]")]
        public string GetElementsAsync([FromBody] IEnumerable<int> elements = default)
        {
            return "value";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • ASP.NET Core 团队在 .NET 7.0 中修复了此问题,因此不再需要设置“内容类型”。https://github.com/dotnet/aspnetcore/pull/38092 (2认同)