2012-03-02 34 views
4

我和行動,這需要userid參數:ASP.net MVC路線的參數異常

〜/用戶/顯示用戶id = 1234

一切正常,除非提供的用戶id不是int或罰款不見了。

然後拋出這個異常:

  Message: The parameters dictionary contains a null entry for parameter 'userId' of 
    non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Show(Int32, 
System.Nullable`1[System.Boolean], System.String)' in 'S4U.Web.Mvc.Controllers.ProfileController'. An optional parameter must be a reference type, 
    a nullable type, or be declared as an optional parameter. 
     Parameter name: parameters 

..after用戶被重定向到錯誤頁面。

我該如何配置路由,以便根本不會觸發該操作,而是會拋出404錯誤?

回答

1

正如我在上UfukHacıoğulları的答案您應該通過增加一個約束的路由處理驗證評論中提及,通過具有可空類型,如果該參數可以是空的。

對於前一種方法,如果您有適當的約束,這意味着您的路線將不會被拾取 - 您將需要捕獲所有路線或其他錯誤處理。對於可爲空的類型,您可以在動作中測試它是否有值並據此採取行動。

將動作參數保持爲強類型是一種旨在實現的模式。

4

不要像下面建議的那樣使用字符串。使用:

public ActionResult (int userId = 0) 
{ 

} 

這是最好的做法。

你也可以這樣做:

public ActionResult (int? userId) 
{ 
    if (userId.HasValue) 
    { 
     //... 
    } 
}