6

I want to have my generic route determine if a query string was passed in the Url like this

http://localhost/query/DailyLogs/1?dateOfLog='1/13/2013'

Here is my current Route definition:

routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "query/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional}
        );

I have read some answers that say to add the dateOfLog value as an optional action on the Route defintion:

routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "query/{controller}/{id}/{dateOfLog}",
            defaults: new { id = RouteParameter.Optional, 
            dateOfLog = RouteParameter.Optional }
        );

This does not seem to work, maybe I am doing something wrong, I am not sure.


This is how I am currently handling the problem, but I would like to use the ModelBinding power of the Routing Engine:

 var queryValue = Request.RequestUri.ParseQueryString();
 string dateOfLog = queryValue["dateOfLog"];

Please tell me how to create a Route definition that will use ModelBinding correctly and map my custom url to the controller's parameters.

1 Answer 1

6

In the controller action, just include DateTime dateOfLog as a method parameter and continue to use the query string as it will get mapped just fine, Web API will use the correct method overload if it finds it.

Sign up to request clarification or add additional context in comments.

4 Comments

I have tried that, with no success. Here is the method signature: public DailyLogResponse Get(int id, DateTime dateOfLog), using the route above this never hits the method.
Ok, try using a string type rather than DateTime in the method parameter.
Yes, you are correct it is actually a DateTime parsing error, when I changed the parameter type to string the method fires and the values are present. Thanks.
That is probably b/c your query-string parameter includes single-quotes, which is unnecessary in a URL. Also, your forward slash date-part separates should be URL encoded

Your Answer

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.