【问题标题】:How to solve action argument type mismatch?如何解决动作参数类型不匹配?
【发布时间】:2012-02-29 20:08:57
【问题描述】:

我的控制器中有一个动作如下。

    //
    // 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”的空条目 方法的不可空类型“System.Int32” 'System.Web.Mvc.ActionResult 详细信息(Int32)' 在 'HostingManager.Controllers.HostingAgrController'。一个可选的 参数必须是引用类型、可为空的类型或声明为 一个可选参数。参数名称:参数

因为 id 在 URL 参数中变成了字符串。我怎样才能在不引发系统错误的情况下处理这种情况?

【问题讨论】:

  • 从标题中删除了ActionResult,因为您谈论的是行动而不是结果。

标签: asp.net-mvc-3 asp.net-mvc-routing


【解决方案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。否则,您将隐藏错误。它今天可能有效,但将来会导致维护混乱。

更新

1fakeid 更改为1 是一种解决方法。这样做是不好的做法。应该强制您的用户输入正确的 ID。

您可以在web.config 中开启customErrors 以隐藏异常详情。

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

【讨论】:

  • 是的,你是对的,我也只尝试过这个解决方案。这是一种解决方法。但我渴望找到可以与“int id”一起使用的真正解决方案。希望有办法做到这一点。
  • 即使我定义了一个整数,恶意用户也可以提交任何东西。在这种情况下,最好有用户友好的处理程序。
  • 没有。如果将 int 作为参数,则除整数之外的任何内容都会出错。
  • @Muneer:你想帮助你的恶意用户吗? ;) 您可以打开 customErrors 以隐藏任何异常详细信息。
  • 您的回复可以作为一种解决方法。顺便说一句,您是否有任何其他想法来处理这种情况,将 ID 保持为 int。
猜你喜欢
  • 2017-01-02
  • 1970-01-01
  • 2022-06-24
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2019-09-23
  • 2011-10-01
相关资源
最近更新 更多