Search code examples
c#asp.net-web-apihttp-get

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 "".


Solution

  • 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