ASP.NET MVC - 正则表达式,错误:参数不能为空。参数名称:输入

时间:2017-06-30 07:27:51

标签: c# asp.net asp.net-mvc

在Tuple方法的第一行中,在表达式Regex.Match中; Parameter can not be null, Parameter name: input给出了错误。 我试过了,但我无法解决问题。我该如何解决?

    public ActionResult Show(string idAndSlug)
    {
        var parts = SeperateIdAndSlug(idAndSlug);
        if (parts == null)
            return HttpNotFound();

        var post = Database.Session.Load<Post>(parts.Item1);
        if (post == null || post.IsDeleted)
            return HttpNotFound();

        if (!post.Slug.Equals(parts.Item2, StringComparison.CurrentCultureIgnoreCase))
            return RedirectToRoutePermanent("Post", new { id = parts.Item1, slug = post.Slug });

        return View(new PostsShow
        {
            Post = post
        });
    }

    private Tuple<int, string> SeperateIdAndSlug(string idAndSlug)
    {
        var matches = Regex.Match(idAndSlug, @"^(\d+)\-(.*)?$");
        if (!matches.Success)
            return null;
        var id = int.Parse(matches.Result("$1"));
        var slug = matches.Result("$2");
        return Tuple.Create(id, slug);
    }

2 个答案:

答案 0 :(得分:0)

确保den Show Action中的参数idAndSlug不为null,否则如果为null则无效。

答案 1 :(得分:0)

确保参数不为空。

public ActionResult Show(string idAndSlug)
{
    if(idAndSlug == null)
        throw new ArgumentNullException(nameof(idAndSlug));
    //your code
}

public ActionResult Show(string idAndSlug)
{
    if(idAndSlug == null)
        idAndSlug = "";
    //your code
}