Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET WEB API Passing DateTime to Controller as part of URI

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.

like image 867
chinabuffet Avatar asked Jun 22 '12 16:06

chinabuffet


2 Answers

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
}
like image 60
The Muffin Man Avatar answered Nov 15 '22 14:11

The Muffin Man


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!

like image 25
stijndepestel Avatar answered Nov 15 '22 15:11

stijndepestel