编写SEO友好的url得到无限循环asp.net

本文关键字:无限循环 asp net url SEO 编写 | 更新日期: 2023-09-27 17:50:44

我正试图为我的网站写SEO友好的URL。为此,我在global.asax.

中编写了以下代码
 protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext incoming = HttpContext.Current;
        string oldpath = incoming.Request.Path;
        string imgId = string.Empty;
        //   string imgName = string.Empty;
        Regex regex = new Regex(@"N/(.+)", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
        MatchCollection matches = regex.Matches(oldpath);
        if (matches.Count > 0)
        {
            imgId = matches[0].Groups[1].ToString();
            // imgName = matches[0].Groups[2].ToString();
            string newPath = String.Concat("~/inner.aspx?Id=", imgId);
            incoming.RewritePath(String.Concat("~/inner.aspx?Id=", imgId), false);
        }
    }

但是当正则表达式匹配时,这段代码进入无限循环。当我在此代码中应用调试器时,当正则表达式匹配时,它会无限移动。

编写SEO友好的url得到无限循环asp.net

问题似乎与正则表达式有关。

这可能是由于过度回溯。在这里查看更多关于回溯的信息

如果您正在使用ASP。然后尝试使用。Net 4.5的新Regex超时特性

您需要注意您的regex设置为忽略大小写,因此n在第一个/之前被捕获。

你需要得到最后一个n和所有不是/的东西:

Regex regex = new Regex(@"N/([^/]+)$", RegexOptions.IgnoreCase);

或者,使用区分大小写的搜索:

Regex regex = new Regex(@"N/(.+)");