如何允许空的请求正文作为引用类型参数?

时间:2019-06-13 11:25:19

标签: c# .net-core get postman

我正在构建.Net Core api控制器,我希望允许用户发送带有或不带有GET类作为参数的MyRequest请求,因此使用{{ 1}}例如可以。

Get(null)请求方法:

GET api/myModels

[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

当我将public class MyRequest { public IEnumerable<string> Filters { get; set; } public string IncludeProperties { get; set; } } 与Body一起使用时,此Get方法有效。 问题是,当我保持主体为空时(使用Postman空对象作为参数,像MyRequest来调用Get方法),我得到了Get(null)的消息:

  

“需要一个非空的请求正文。”

有一个类似的question,但是那里的参数是值类型。

2 个答案:

答案 0 :(得分:9)

执行此操作:

  services.AddControllersWithViews(options =>
  {
       options.AllowEmptyInputInBodyModelBinding = true;
  });

答案 1 :(得分:1)

您可以通过指定默认值null并明确指定这些值将作为请求url的一部分来使其成为可选参数

[HttpGet]
public ActionResult<IEnumerable<MyModel>> Get([FromQuery]MyRequest myRequest = null)
{

顺便说一句,GET操作没有正文,因此所有端点参数都应通过查询字符串(Or)作为Route值传递。

您应该在api端点中指定一个路由,并通过route和querystring传递值。像

[HttpGet("{IncludeProperties}")]
//[Route("{IncludeProperties}")]
public ActionResult<IEnumerable<MyModel>> Get(string IncludeProperties = null, IEnumerable<string> Filters = null)
{

现在有了上述内容,您可以像请求API一样

GET api/myModels?Filters=