首页 文章

如何解决动作参数类型不匹配?

提问于
浏览
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);
    }

现在,如果我像下面这样调用URL ..(用于测试目的)

/HostingAgr/Details/1fakeid

系统将抛出异常 .

参数字典包含非可空类型'System.Int32'的参数'id'的空条目,用于'HostingManager.Controllers.HostingAgrController'中方法'System.Web.Mvc.ActionResult Details(Int32)' . 可选参数必须是引用类型,可空类型,或者声明为可选参数 . 参数名称:参数

因为id在URL参数中成为字符串 . 如何在不抛出系统错误的情况下处理这种情况?

1 回答

  • 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 . 否则你隐藏了错误 . 它可能在今天工作,但它将导致未来的维护混乱 .

    Update

    1fakeid 更改为 1 的任何内容都是一种解决方法 . 这样做很糟糕 . 您应该强制用户输入正确的ID .

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

    如果您仍想继续,我认为您可以通过添加自定义 ValueProviderFactory 来解决问题 .

相关问题