2

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

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

3 Comments

But you could for better transparency and code style?
@liqSTAR definitely that's an option, it comes down to the preference and defined style indeed. In my opinion decorating params with the same attribute adds noise to the method signature. I would use it only in situation when there are different sources to bind model from. (e.g. ApiMethod([FromUri] string p1, [FromBody] string p2, [FromHeader] string p3))
How to pass string model as optional parameter here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.