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.
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.
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.
In this case you get a the original string back as a JSON response – JSON because the default format for Web API is JSON.
Do this:
services.AddControllersWithViews(options =>
{
options.AllowEmptyInputInBodyModelBinding = true;
});
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=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With