关于c#:使用2个Get方法重载Web API控制器

Overloading WebAPI controller with 2 Get methods

我有2种操作方法的webapi控制器,如下所示:

1
2
3
4
5
6
7
8
9
public List<AlertModel> Get()
{
    return _alertService.GetAllForUser(_loginService.GetUserID());
}

public AlertModel Get(int id)
{
    return _alertService.GetByID(id);
}

但是,当我向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'. An optional parameter must be a
reference type, a nullable type, or be declared as an optional
parameter.

我在global.asax中设置了以下路由:

1
routes.MapHttpRoute("Api","api/{controller}/{id}", new { id = UrlParameter.Optional });

这种类型的重载应该起作用吗?如果我应该怎么做呢?

编辑

尽管此问题是关于WebAPI的,但控制器是MVC3项目的一部分,这些是其他MapRoutes

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


问题是您使用的是UrlParameter.Optional(这是ASP.NET MVC的特定类型),而不是RouteParameter.Optional。如下更改您的路线,然后它应该起作用:

1
2
3
4
5
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
   "Api",
   "api/{controller}/{id}",
    new { id = RouteParameter.Optional }
);