ASP.NET Web Interface API Pass 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 would like to have access to the method when passing the date as part of the URI itself, but currently I can only make it work when passing the date as a query string. For instance:

 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 make this work? I tried playing with custom MediaTypeFormatters, but although I add them to the HttpConfiguration Formatters list, they never execute.

+4
source share
2 answers

Look at your default MVC routing code:

 routes.MapRoute( "Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", **id** = UrlParameter.Optional} ); 

Good. See Name Identifier? You need to specify your id method parameter so that the middleware knows that you want to bind to it.

Use it -

 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 } 
+3
source

If you want to pass it as part of the URI itself, you need to consider the default routing defined in Global.asax. If you did not change it, it indicates that the URI breaks into / Controller / action / id.

For example, uri 'Home / Index / hello' translates to Index ("hello") in the HomeController class.

Therefore, in this case, it should work if you change the name of the DateTime parameter to "id" instead of "date".

It may also be safer to change the type of the parameter from 'DateTime' to 'DateTime?' to prevent mistakes. And as a second note, all controller methods in the mvc template must return an ActionResult object.

Good luck

+3
source

All Articles