+ -
当前位置:首页 → 问答吧 → 关于ASP.NET MVC3中用正则判断ID是否是数字的问题

关于ASP.NET MVC3中用正则判断ID是否是数字的问题

时间:2011-12-10

来源:互联网

我给点的重要的代码吧

C# code

 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,而是直接报错了。
报错代码如下:

HTML code

“/”应用程序中的服务器错误。
对于“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





我应该怎么处理这个问题?

作者: postcha   发布时间: 2011-12-10

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

作者: soonfei   发布时间: 2011-12-10

好像正则没有错啊!

对于“Blog.Controllers.ReadController”中方法“System.Web.Mvc.ActionResult Blog(Int32)”的不可以为 null 

这一句

作者: soonfei   发布时间: 2011-12-10

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

作者: Return_false   发布时间: 2011-12-10

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());





作者: Sandy945   发布时间: 2011-12-12

相关阅读 更多