[英]Overloading WebAPI controller with 2 Get methods
I have webapi controller with 2 action methods like so: 我有webapi控制器,有2个动作方法,如下所示:
public List<AlertModel> Get()
{
return _alertService.GetAllForUser(_loginService.GetUserID());
}
public AlertModel Get(int id)
{
return _alertService.GetByID(id);
}
However, when I make a request to api/alerts
I get the following error: 但是,当我向api/alerts
请求时,我收到以下错误:
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'ekmSMS.Common.Models.AlertModel Get(Int32)' in 'ekmSMS.Web.Api.AlertsController'. 参数字典包含'ekmSMS.Web.Api.AlertsController'中方法'ekmSMS.Common.Models.AlertModel Get(Int32)'的非可空类型'System.Int32'的参数'id'的空条目。 An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. 可选参数必须是引用类型,可空类型,或者声明为可选参数。
I have the following route set up in global.asax
: 我在global.asax
设置了以下路由:
routes.MapHttpRoute("Api", "api/{controller}/{id}", new { id = UrlParameter.Optional });
Should this type of overloading work? 这种类型的超载是否有效? And if it should what am I doing wrong? 如果它应该是我做错了什么?
EDIT 编辑
Although this question is about WebAPI, the controllers are part of a MVC3 project, these are the other MapRoutes
: 虽然这个问题与WebAPI有关,但控制器是MVC3项目的一部分,这些是其他MapRoutes
:
routes.MapRoute("Templates", "templates/{folder}/{name}", new { controller = "templates", action = "index", folder = "", name = "" });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "app", action = "index", id = UrlParameter.Optional });
The problem is that you used UrlParameter.Optional
(which is an ASP.NET MVC specific type) instead of RouteParameter.Optional
. 问题是您使用UrlParameter.Optional
(这是一种ASP.NET MVC特定类型)而不是RouteParameter.Optional
。 Change your route as below and then it should work: 如下更改您的路线然后它应该工作:
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
"Api",
"api/{controller}/{id}",
new { id = RouteParameter.Optional }
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.