Asp.net mvc 3 如何解决操作参数类型不匹配?

Asp.net mvc 3 如何解决操作参数类型不匹配?,asp.net-mvc-3,asp.net-mvc-routing,Asp.net Mvc 3,Asp.net Mvc Routing,我的控制器中有一个操作,如下所示 // // GET: /HostingAgr/Details/1 public ActionResult Details(int id) { HostingAgreement hosting = hmEntity.HostingAgreements.SingleOrDefault(h => h.AgreementId == id); if (hosting == null) {

我的控制器中有一个操作,如下所示

    //
    // 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);
    }
现在,如果我像下面这样调用URL。。(用于测试目的)

系统将抛出异常

参数字典包含的参数“id”为空 方法的不可为Null的类型“System.Int32” 中的“System.Web.Mvc.ActionResult详细信息(Int32)” 'HostingManager.Controller.HostingAgrController'。可选的 参数必须是引用类型、可为null的类型或声明为 可选参数。参数名称:参数


因为id在URL参数中变为字符串。如何在不引发系统错误的情况下处理此情况?

接受字符串并尝试转换它:

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。否则,您将隐藏错误。它可能在今天起作用,但将来会导致维护混乱

更新

任何将
1akeid
更改为
1
的操作都是一种变通方法。这样做是不好的做法。应该强制用户输入正确的ID

您可以在
web.config
中打开
customErrors
,以隐藏异常详细信息


如果您仍然想继续,我认为您可以通过添加自定义的
ValueProviderFactory

来解决问题,因为您谈论的是操作而不是结果,因此从标题中删除了
ActionResult
。是的,您是对的,我也只尝试了此解决方案。这是一个变通办法。但我渴望找到与“intid”匹配的真正解决方案。希望有办法。即使我定义了整数,恶意用户也可以提交任何内容。在这种情况下,最好使用用户友好的handler.No。如果将int作为参数,则除整数以外的任何内容都会出现错误。@Muneer:您想帮助恶意用户吗?;)您可以打开
customErrors
以隐藏任何异常详细信息。您的答复可以作为一种解决方法。顺便说一句,你有没有其他办法处理这种情况,保持ID为int。
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);
}