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.
-
what do the routes for your service look like ?cecilphillip– cecilphillip2012年06月23日 15:01:42 +00:00Commented Jun 23, 2012 at 15:01
2 Answers 2
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
}
Comments
If you want to pass it as part of the URI itself you have to consider the default routing which is defined in the Global.asax. If you haven't changed it, it states that the URI breaks down in /Controller/action/id.
For example the uri 'Home/Index/hello' translates into Index("hello) in the HomeController class.
So in this case it should work if you changed the name of the DateTime parameter to 'id' instead of 'date'.
It also might be safer to change the type of the parameter from 'DateTime' to 'DateTime?' to prevent errors. And as a second remark, all controller methods in the mvc pattern should return an ActionResult object.
Good luck!