我给点的重要的代码吧
 public ActionResult Blog(int id)
        {
            Regex reg = new Regex("^[0-9]+$");
            Match ma = reg.Match(id.ToString());
            if (!ma.Success)
            {
                return RedirectToAction("Error");
            }
            else
            {
             
            var article = db.Articles.Find(id);
            if (article == null)
            {
                return RedirectToAction("Error");
            }
            else
            {
                articlerepository.UpdateCount(id);
                ViewBag.sitename = db.BlogConfigs.First().BlogName;
这里我主要是防止用户输入非纯数字。
当id不是一个数字时,就跳转到action Error上。
可是我在测试时,当id是一个数字时,则正常。而当id不是一个数字时,没有跳转到Error,而是直接报错了。
报错代码如下:
“/”应用程序中的服务器错误。
对于“Blog.Controllers.ReadController”中方法“System.Web.Mvc.ActionResult Blog(Int32)”的不可以为 null 的类型“System.Int32”的参数“id”,参数字典包含一个 null 项。可选参数必须为引用类型、可以为 null 的类型或声明为可选参数。
参数名: parameters
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。异常详细信息: System.ArgumentException: 对于“Blog.Controllers.ReadController”中方法“System.Web.Mvc.ActionResult Blog(Int32)”的不可以为 null 的类型“System.Int32”的参数“id”,参数字典包含一个 null 项。可选参数必须为引用类型、可以为 null 的类型或声明为可选参数。
参数名: parameters
我应该怎么处理这个问题?

解决方案 »

  1.   

    把上面那一点改成这样:
    Regex reg = new Regex("^[0-9]+$");
            string result = id.ToString();
            
            if (!reg.IsMatch(result))
            {
                return RedirectToAction("Error");
            }
      

  2.   

    好像正则没有错啊!对于“Blog.Controllers.ReadController”中方法“System.Web.Mvc.ActionResult Blog(Int32)”的不可以为 null 这一句
      

  3.   

    错误已经很明确了,修改如下,可以接受null的id
    public ActionResult Blog(int? id)
      

  4.   

    public ActionResult Blog(int id)
    =>
    public ActionResult Blog(int? id)Regex reg = new Regex("^[0-9]+$");
    Match ma = reg.Match(id.ToString());
    =>
    if(!id.HasValue)
       RedirectToAction("Error");
    Regex reg = new Regex("^[0-9]+$");
    Match ma = reg.Match(id.Value.ToString());
      

  5.   

    我晕,你方法中都写成了INT ID了,还判断个啥,不是数字直接跑到出错页了,没必要在做什么判断
      

  6.   

    用了HandleError+<customErrors mode="On"></customErrors>解决。