WebApi optional parameter - is required?

最后都变了- 提交于 2019-12-08 16:38:38

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/13893793/webapi-optional-parameter-is-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!