2014-05-19 51 views
1

我配置了這樣的路線:ASP.net網頁API 2錯誤「的參數字典包含參數無效項」

routes.MapHttpRoute("DefaultApi2", "api/{controller}/{action}/{id}", new {id = RouteParameter.Optional} 

和我的控制器看起來是這樣的:

public class RoutineController : ApiController 
{ 
    private readonly RoutineService _routineService; 

    public RoutineController(RoutineService routineService) 
    { 
     _routineService = routineService; 
    } 



    [HttpGet] 
    [ActionName("Tags")] 
    public List<RoutineTag> Tags() 
    { 
     return _routineService.GetAllTags(); 
    } 

    [HttpGet] 
    [ActionName("SingleRoutine")] 
    // GET api/routine/5 
    public RoutineViewModel SingleRoutine(int id) 
    { 
     return _routineService.GetRoutineById(id); 

    } 
} 

但如果我改變方法SingleRoutine這個

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'Infrastructure.Api.Models.RoutineViewModel Routine(Int32)' in 'Infrastructure.Api.Controllers.RoutineController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."} 

:我得到這個錯誤

[HttpGet] 
    [ActionName("SingleRoutine")] 
    // GET api/routine/5 
    public RoutineViewModel SingleRoutine(int? id) 
    { 
     if (!id.HasValue) 
     { 
      return null; 
     } 
     return _routineService.GetRoutineById((int) id); 
} 

在瀏覽器中我只看到「null」。

這是怎麼發生的?

EDIT

當我輸入/ API /例程/標籤

+0

錯誤在哪一行發生?我敢打賭它不在這裏。 –

+0

異常不會拋出,這個錯誤顯示在瀏覽器 – hyperN

+0

我不知道它是否重要,但我使用Niject作爲IoC – hyperN

回答

4

我相信這是WebApiConfig問題,我有以下行:

config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional} 
      ); 

     config.Routes.MapHttpRoute("CustomApi", "{controller}/{action}/{id}", new {id = RouteParameter.Optional} 
      ); 

並且在路由配置中

現在WebApiConfig我:

config.Routes.MapHttpRoute("CustomApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional } 
     ); 
     config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional} 
      ); 

並在RouteConfig:

routes.MapRoute(
      name: "Default", 
      url: "{controller}/{action}/{id}", 
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
     ); 

和它的作品!

+1

請在您的問題的更新中包括此。所有這些信息你應該提供你的問題。 – Guanxi

+1

@Guanxi但是,這是解決方案,現在它的工作原理,爲什麼我應該把它放在問題? – hyperN

1

爲API/{控制器}/{行動}/{ID}路線URL API示出/例程此錯誤/ 5搜索對於功能(作用),5是不是有

更新:

你的錯誤信息是有原因的,爲什麼它失敗:的選項al參數必須是參考類型,可爲空類型,或者聲明爲可選參數。「}

int不可爲空,因此當您不提供其值時,它無法創建id。

+0

我編輯了我的問題,當我嘗試去路由api /例程/標籤時發生問題 – hyperN

+0

我也更新了我的答案。 – Guanxi

+0

但是,當我改變它爲int? null在瀏覽器中顯示,這意味着代替標籤,SingleRoutine被調用? – hyperN

1

使用基於公約路由(安裝NuGet包)在您的網頁API

附加定義下列類型的路線

[Route("api/routine/{id}")] 
相關問題