Search code examples
c#asp.net-web-apiasp.net-web-api-routingattributerouting

Attribute routing recognize optional query string parameters


I have a API action:

 [HttpGet, Route("{id}/overview/")]
 public async Task<HttpResponseMessage> Overview(string id, DateTime from, DateTime? to)
{
...
}

As you noticed, to is optional parameters, but when I make request:

'/api/cream/3d7dd454c00b/overview?from=2016-09-04T18:00:00.000Z

I got 404 error. If I delete to from parameters: public async Task<HttpResponseMessage> Overview(string id, DateTime from)

then all works fine. How to force it work with to parameters?


Solution

  • Use the FromUri attribute and make to optional

    
    
        [HttpGet, Route("{id}/overview/")]
         public async Task Overview(string id, [FromUri]DateTime from, [FromUri]DateTime? to = null)
        {
        ...
        }
    
    

    To expand on this the id parameter is picked up because you have specified it in your route, the framework has seen a matching route and tried to call the method which matches, even though the route is missing the remaining parameters it has tried to pull them from the query string.

    You then get your 404 as no method matched your call, this was due to the to DateTime being nullable but not optional.

    Hope this helps