【发布时间】:2015-08-06 23:28:00
【问题描述】:
我正在尝试为我的网站编写 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);
}
}
但是当正则表达式匹配时,这段代码会无限循环。当我在这段代码中应用调试器时,当正则表达式匹配时它会无限移动。请帮我解决这个问题。
【问题讨论】:
-
它与正则表达式无关,它匹配一个
n或N,然后是一个/,然后是除换行符之外的0个或多个字符。输入是什么?如果您的模式中不使用空格,为什么要使用IgnorePatternWhitespace?冻结发生在哪一行? -
在应用调试器时,我得到的是当 URL 符合正则表达式时,事件 Application_BeginRequest 被一次又一次地触发。我认为这个问题与正则表达式无关。
-
例如,当用户编写像 www.upnews360.in/N/xyz 这样的 URL 时,它会被重写为 www.upnews360.in/inner.aspx?Id=xyz。
-
您的代码正确地到达了
string newPath行,而newPath是~/inner.aspx?Id=N/xyz。你需要一个正则表达式修复。我想我有一个解决方案。 -
是的,我的代码正确地获取了新路径,即 ~/inner.aspx?Id=N/xyz。但是在这段代码中应用调试器时,我看到了非常意想不到的行为。它不断地前进。我还按照您的建议更改了正则表达式,但没有帮助。
标签: c# asp.net regex url-rewriting