WebApi可选参数-是必需的吗? [英] WebApi optional parameter - is required?

查看:586
本文介绍了WebApi可选参数-是必需的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web api控制器(TasksController),其get方法类似于:

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

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

如果我打电话

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

返回正确的结果。

如果我打电话

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

然后我得到:

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

任何想法为什么会这样?
谢谢。

Any idea why this happens ? Thanks.

编辑:
这是路由配置中的内容:

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


推荐答案

您的首次通话:
/ api / tasks?startDate = 2012%2F12%2F08& endDate = 2012%2F12%2F15
如何调用带有可选参数的方法参数(即参数是可选的,因此您未指定它)。当您在查询字符串中指定& projectCode =时,您指定参数,并且将其指定为 null 。由于字符串可以为空,因此api假定您想要发送空值。如果您希望该方法以空字符串运行,则只需按以前的方式进行调用即可,而无需发送该参数。

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.

这篇关于WebApi可选参数-是必需的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆