I am trying to write SEO friendly URL for my website. for this I have written following code in my 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);
}
}
But When the regular expression matches, this code goes on infinite loop. When I apply debugger in this code, It moves infinitely when the regular expression Matches. Please help me regarding this problem.
2
Answers
It seems problem related to Regex.
It can be due to excessive backtracking. See more about backtracking here
If you are using ASP.Net version 4.5 then try to use .NET 4.5’s new Regex timeout feature here
You need to be aware that your regex is set to ignore case, thus
n
is caught before the first/
.You need either to get the last
n
and everything that is not/
:Or, use a case sensitive search: