8

I have a web api controller (TasksController) with a get method like :

public IEnumerable<TimeUnitModel> Get(DateTime startDate, DateTime endDate, string projectCode = "")

If I call

/api/tasks?startDate=2012%2F12%2F08&endDate=2012%2F12%2F15

the correct result is returned.

If I call

/api/tasks?startDate=2012%2F12%2F08&endDate=2012%2F12%2F15&projectCode=

then I get :

{"projectCode.String":"A value is required but was not present in the request."}

Any idea why this happens ? Thanks.

Edit: Here's what I have in the route config :

config.Routes.MapHttpRoute(
            name: "tasks_get",
            routeTemplate: "api/tasks",
            defaults: new { controller = "tasks", projectCode = RouteParameter.Optional}
        );
sirrocco
  • 7,975
  • 4
  • 59
  • 81
  • 1
    @sirrocco I have seen similar behaviour to this before, on this question http://stackoverflow.com/questions/12006524/why-does-modelstate-isvalid-fail-for-my-apicontroller-method-that-has-nullable-p/12622152#12622152 – Mark Jones Dec 15 '12 at 18:41
  • 1
    P.s. projectCode is in the query string not the path and therefore not a route parameter - so you can remove optional parameter bit from config. – Mark Jones Dec 15 '12 at 18:48
  • Thanks Mark. I'll also take a look in the framework just out of curiosity. And yes, you are correct about it not being a route parameter but I just had to try it :) . – sirrocco Dec 15 '12 at 18:59

1 Answers1

3

Your first call: /api/tasks?startDate=2012%2F12%2F08&endDate=2012%2F12%2F15 is how you call the method with an optional parameter (i.e. the parameter is optional, so you are not specifying it). When you specify "&projectCode=" in the query string, you are specifying the parameter, and you're specifying it as null. Since strings are nullable, the api assumes you want to send in a null value. If you want the method to run with an empty string, just call it the way you were doing before without sending in that parameter at all.

codeMonkey
  • 4,134
  • 2
  • 31
  • 50