5

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.

wonea
4,98917 gold badges91 silver badges143 bronze badges
asked Jun 22, 2012 at 16:30
1
  • what do the routes for your service look like ? Commented Jun 23, 2012 at 15:01

2 Answers 2

3

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
}
answered Jul 8, 2012 at 8:42

Comments

3

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!

answered Jul 8, 2012 at 8:36

3 Comments

If you really want to name the paramater 'date' you can always register a new route in your global.asax file.
"Assuming you work in ASP.NET MVC framework." The question is tagged MVC.
New here, just trying to help out.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.