简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM