1

I have an action with two required and a few optional parameters:

[HttpGet] public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode, int? countryId) { using (DataHandler handler = new DataHandler()) return Ok(handler.GetUsers(dateFrom, dateTo).ToList()); } 

I want an url like this one:

/api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002&countryId=4 

zipcode and countryId are optional and will be added with the ?-thingy. The required parameters dateFrom and dateTo will be added with /

so following urls should be possible too:

/api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4 /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002 /api/getusers/2018-12-03T07:30/2018-12-03T12:45 

I tried a few routings like

[Route("getusers/{dateFrom}/{dateTo}")] [Route("getusers/{dateFrom}/{dateTo}*")] [Route("getusers/{dateFrom}/{dateTo}**")] [Route("getusers/{dateFrom}/{dateTo}?zipcode={zipcode}&countryId={countryId}")] 

but none of them are working. When I remove the optional parameters it works, but I need those optional ones.

Any idea how to get this done?

1 Answer 1

4

Make the optional parameters optional in the action method

If a route parameter is optional, you must define a default value for the method parameter.

//GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?countryId=4 //GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45?zipcode=4002 //GET /api/getusers/2018-12-03T07:30/2018-12-03T12:45 [HttpGet] [Route("getusers/{dateFrom:datetime}/{dateTo:datetime}")] public IHttpActionResult GetUsers(DateTime dateFrom, DateTime dateTo, string zipcode = null, int? countryId = null) { using (DataHandler handler = new DataHandler()) return Ok(handler.GetUsers(dateFrom, dateTo).ToList()); } 

Reference Attribute Routing in ASP.NET Web API 2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.