2012-02-29 31 views
0

我在我的控制器中有一個動作如下。如何解決動作參數類型不匹配?

// 
    // GET: /HostingAgr/Details/1 
    public ActionResult Details(int id) 
    { 
     HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == id); 
     if (hosting == null) 
     { 
      TempData["ErrorMessage"] = "Invalid Agreement ID"; 
      return RedirectToAction("Index"); 
     } 

     return View(hosting); 
    } 

現在,如果我把網址,如下所示。(用於測試目的)

/HostingAgr/Details/1fakeid 

系統會拋出異常。

參數字典包含參數 非空類型「System.Int32」的方法 「System.Web.Mvc.ActionResult詳細信息(的Int32)」在 「HostingManager的「ID」一個空條目。 Controllers.HostingAgrController」。可選 參數必須是參考類型,可爲空類型,或者聲明爲可選參數 。參數名稱:參數

因爲id在URL參數中變成了字符串。我如何處理這種情況而不會引發系統錯誤?

+0

由於您正在討論操作而不是結果,因此從標題中刪除了「ActionResult」。 – jgauffin 2012-02-29 09:49:07

回答

1

接受一個字符串,並嘗試將其轉換:

public ActionResult Details(string id) 
{ 
    var numericId; 
    if (!int.TryParse(id, out numericId)) 
    { 
     // handle invalid ids here 
    } 

    HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == numericId); 
    if (hosting == null) 
    { 
     TempData["ErrorMessage"] = "Invalid Agreement ID"; 
     return RedirectToAction("Index"); 
    } 

    return View(hosting); 
} 

我不建議你這麼做。無效的ID應被視爲無效的ID。否則,你正在隱藏錯誤。它今天可能會有效,但它會導致未來的維護混亂。

更新

任何改變1fakeid1是一種解決方法。這樣做是不好的做法。你的用戶應該被迫輸入正確的ID。

您可以在web.config中打開customErrors以隱藏異常詳細信息。

如果你仍然想繼續我認爲你可以通過添加一個自定義ValueProviderFactory解決問題。

+0

是的你是對的,我也試過這個解決方案。這是一種解決方法。但我急於找到可以使用「int id」的真正解決方案。希望可能有辦法做到這一點。 – BlueBird 2012-02-29 09:53:28

+0

你不會。 '1fakeid'不是一個正確的ID。 – jgauffin 2012-02-29 09:59:45

+0

即使我定義了整數,惡意用戶也可以提交任何內容。在那種情況下,最好有用戶友好的處理程序。 – BlueBird 2012-02-29 10:13:46

相關問題