8

I have a WebAPI 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

then 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."}

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}
);

Any idea why this happens?

3
  • 1
    @sirrocco I have seen similar behaviour to this before, on this question stackoverflow.com/questions/12006524/… Commented Dec 15, 2012 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. Commented Dec 15, 2012 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 :) . Commented Dec 15, 2012 at 18:59

1 Answer 1

4

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.

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

Comments

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.