skip to Main Content

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.



  1. 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

    Login or Signup to reply.
  2. 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 /:

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

    Or, use a case sensitive search:

    Regex regex = new Regex(@"N/(.+)");
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top