我的控制器中有一个操作,如下所示。
//
// 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
系统将引发异常。
参数字典包含的参数"id"的null条目方法的类型"System.Int32"不可为null中的"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。否则,您将隐藏错误。它今天可能工作,但将来会导致维护混乱。
更新
任何将1fakeid
更改为1
的操作都是一种变通方法。这样做是不好的做法。你的用户应该被迫输入正确的id。
您可以在web.config
中打开customErrors
以隐藏异常详细信息。
如果您仍然想继续,我认为您可以通过添加自定义ValueProviderFactory
来解决问题。