Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 370
Shahar Shokrani Avatar asked Jun 13 '19 11:06

Shahar Shokrani


People also ask

Can you add body to get request?

Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request.

What is a Requestbody?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.

Which is the default formatter for the incoming request body?

In this case you get a the original string back as a JSON response – JSON because the default format for Web API is JSON.


2 Answers

Do this:

  services.AddControllersWithViews(options =>
  {
       options.AllowEmptyInputInBodyModelBinding = true;
  });
like image 199
code5 Avatar answered Oct 12 '22 22:10

code5


You can make it a optional parameter by assigning a default value null and specifying explicitly that the values will be coming as part of request url

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

BTW, a GET operation has no body and thus all the endpoint parameter should be passed through query string (Or) as Route value.

You should specify a routing in your api end point and have the values passed through route and querystring. something like

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

With the above in place now you can request your api like

GET api/myModels?Filters=
like image 28
Rahul Avatar answered Oct 12 '22 22:10

Rahul