使用2 Get方法重载Web API控制器

时间:2012-08-03 11:24:38

标签: c# .net asp.net-web-api

我有webapi控制器,有两种动作方法,如:

public List<AlertModel> Get()
{
    return _alertService.GetAllForUser(_loginService.GetUserID());
}

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

但是,当我向api/alerts发出请求时,我收到以下错误:

  

  参数字典包含参数'id'的空条目   方法的非可空类型'System.Int32'   'ekmSMS.Common.Models.AlertModel获取(Int32)'in   'ekmSMS.Web.Api.AlertsController'。可选参数必须是a   引用类型,可空类型,或声明为可选   参数。

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

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

这种类型的重载是否有效?如果它应该是我做错了什么?

修改

虽然这个问题与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 });

1 个答案:

答案 0 :(得分:12)

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

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    "Api",
    "api/{controller}/{id}",
    new { id = RouteParameter.Optional }
);
相关问题