Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Web API Optional parameters in query string

I have this piece of code in my controller:

[HttpGet]
[Route("team={team}&model={model}&date={date}&distance={distance}")]
public IHttpActionResult FindVehicle([FromUri]string team = "", [FromUri]string model = "", [FromUri]DateTime? date = null, [FromUri]double distance = 0.0)
    { }

All of the parameters of the query string can be optional, which is why I used the default values.

However, I am not sure what the route should be, since now, when I don't specify the model parameter for example, its value in the endpoint ends up being "model", and not "".

like image 550
Eutherpy Avatar asked Dec 14 '25 18:12

Eutherpy


1 Answers

You don't have to define FromUri elements inside Route attribute, they will be bound out of the box:

[HttpGet]
[Route("route_name")]
public IHttpActionResult FindVehicle([FromUri]string team = "", [FromUri]string model = "", [FromUri]DateTime? date = null, [FromUri]double distance = 0.0)
{ 

}

If you are using, ASP.Net Core, then you should use [FromQuery] instead

like image 88
Darjan Bogdan Avatar answered Dec 17 '25 11:12

Darjan Bogdan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!