How to pass DateTime parameter using Web API attribute routing?

18,621

The problem is that : is a URL reserved character in the path. MVC doesn't expect it to be URL encoded and won't handle it. However, it is not reserved in the query string.

Remove it from your routing specification, but leave them as parameters in your method and the model binder will bind them. Alternatively, you can also remove them as parameters and access them via the Context query string property or ControllerContext.Request.GetQueryNameValuePairs().

So you would have ?fromDate=2012-01-01T1:45:30PM&toDate=2013-01-01T1:45:30PM

Share:
18,621
Georges
Author by

Georges

Updated on June 17, 2022

Comments

  • Georges
    Georges almost 2 years

    I am working on a REST API with ASP.NET Web API 2. Thing get bad when I try to integrate dates into the game.

    Here is the route:

    [Route("{id:Guid}/{from:DateTime}/{to:DateTime}")]
    

    When I do that I can perfectly pass something like

    .../[id]/2012-01-01/2013-01-01
    

    However, when I get to the point where I need the time information it gets quite bad, let's imagine this one:

    .../[id]/2012-01-01/2013-01-01 1:45:30 PM/2013-01-01 1:45:30 PM
    

    It seems like the spaces are going OK but the ":" are blocking. So I though I should use my own format, being yyyyMMddhhmm. This gives the following URL:

    .../[id]/201301031147/201401031147
    

    However, .NET is not expecting this as a DateTime and does not know how to use it. So I used a IHttpRouteConstraint to allow it. The problem is that it still does not know how to deal with it after I told it it's fine...

    So my question is, how do you pass a DateTime to the route?