ASP.NET WEB API Passing DateTime to Controller as part of URI
asp.net-mvc, asp.net-web-api, rest
Solution
Let's look at your default MVC routing code:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", **id** = UrlParameter.Optional}
);
Okay. See the name id? You need to name your method parameter "id" so the model binder knows you that you want to bind to it.
Use this -
public int Get(DateTime id)// Whatever id value I get try to serialize it to datetime type.
{ //If I couldn't specify a normalized NET datetime object, then set id param to null.
// return count from a repository based on the date
}
Problem
Say I have a Controller with the following method: ``` public int Get(DateTime date) { // return count from a repository based on the date } ``` I'd like to be able to access method while passing the date as part of the URI itself, but currently I can only get it to work when passing the date as a query string. For example: ``` Get/2012-06-21T16%3A49%3A54-05%3A00 // does not work Get?date=2005-11-13%205%3A30%3A00 // works ``` Any ideas how I can get this to work? I've tried playing around with custom MediaTypeFormatters, but even though I add them to the HttpConfiguration's Formatters list, they never seem to be executed.