c# - How to allow an empty request body for a reference type parameter?
问题描述
I'm Building an .Net Core api controller, I would like to allow users to send GET
requests with or without the MyRequest
class as a parameter, so the calling the method with Get(null)
for example will be Ok.
GET api/myModels
requests method:
[HttpGet]
public ActionResult<IEnumerable<MyModel>> Get(MyRequest myRequest)
{
if (myRequest == null)
myRequest = new myRequest();
var result = this._myService.Get(myRequest.Filters, myRequest.IncludeProperties);
return Ok(result);
}
MyRequest
class:
public class MyRequest
{
public IEnumerable<string> Filters { get; set; }
public string IncludeProperties { get; set; }
}
When I refer to this Get
method using Postman
with Body, it works.
The problem is, when I keep the body empty (to call the Get method with a MyRequest
null object as a parameter like Get(null)
) I'm getting this Postman
's massage of:
"A non-empty request body is required."
There is a similar question, but there, the parameters are value type.
解决方案
做这个:
services.AddControllersWithViews(options =>
{
options.AllowEmptyInputInBodyModelBinding = true;
});
推荐阅读
- c# - .NET 框架是否有任何易于插入的官方 RBAC 实现?
- javascript - React hooks - useState() 中的状态在路由更改时不会重置
- python - 为 OCR 准备图像
- python - 如何在数据框的列中找到最大值?
- java - 使用 Prometheus 监控 Java 独立应用程序
- go - Artifactory中go项目的远程存储库不代理?
- java - 如何在 Java 中从另一个 dataFrame 中 flatMap 一个 dataFrame?
- powershell - 如何从查询的数据中获取唯一的值
- s4sdk - SpringBoot jar中ODataApplicationInitializer的空指针异常
- ruby-on-rails - 模型显示的友好 ID 未按预期工作。有什么办法解决这个问题吗?