4

次のような2つのアクションメソッドを持つwebapiコントローラーがあります。

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

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

ただし、リクエストを行うapi/alertsと、次のエラーが発生します。

パラメータ ディクショナリには、「ekmSMS.Web.Api.AlertsController」のメソッド「ekmSMS.Common.Models.AlertModel Get(Int32)」の null 非許容型「System.Int32」のパラメータ「id」の null エントリが含まれています。オプションのパラメーターは、参照型または null 許容型であるか、オプションのパラメーターとして宣言する必要があります。

に次のルートを設定しました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 });
4

1 に答える 1

12

問題は、UrlParameter.Optional代わりに (ASP.NET MVC 固有の型である) を使用したことですRouteParameter.Optional。以下のようにルートを変更すると、動作するはずです。

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    "Api",
    "api/{controller}/{id}",
    new { id = RouteParameter.Optional }
);
于 2012-08-03T12:40:36.560 に答える