Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass DateTime parameter using Web API attribute routing?

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?

like image 375
Georges Avatar asked Jan 03 '14 12:01

Georges


People also ask

How do you pass date parameters?

Answer. The passing of Date parameters is done in a very specific format, based on the International Date formatting standard. For any Cognos software , parameters specified in the URL for a date / time parameter, should not include a value for milliseconds, and this value should be set to zero.

What are the different ways to pass parameters in Web API?

Passing Data in your API Calls REST API endpoints can pass data within their requests through 4 types of parameters: Header, Path, Query String, or in the Request Body.

How do I pass a date in query string?

string dateTime = Request. QueryString["DateStarted"]; DateTime dt = Convert. ToDateTime(dateTime); Response.


1 Answers

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

like image 106
Geoff Cox Avatar answered Oct 11 '22 08:10

Geoff Cox