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)
编辑:澄清一下:
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)
| 归档时间: |
|
| 查看次数: |
21440 次 |
| 最近记录: |