Do you need an optional WebApi parameter?

I have a web-api controller (TasksController) with a get method, for example:

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

If i call

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

returns the correct result.

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 is happening? Thanks.

Edit: Here is what I have in the route configuration:

 config.Routes.MapHttpRoute( name: "tasks_get", routeTemplate: "api/tasks", defaults: new { controller = "tasks", projectCode = RouteParameter.Optional} ); 
+7
source share
1 answer

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

+2
source

All Articles