首页 > 解决方案 > 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.

标签: c#.net-coregetpostman

解决方案


做这个:

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

推荐阅读