asp net global asax rewrite infinite loop

183 views Asked by At

Here my Global.asax

   public void GetRewrites()
   {
      if (rewrites == null)
         rewrites = Rewrite.getRules(); //reads from the DB
   }

   protected void Application_Start(object sender, EventArgs e)
   {
      RouteTable.Routes.Clear();
      RouteTable.Routes.EnableFriendlyUrls();
      RouteTable.Routes.MapPageRoute("", "home", "~/Default.aspx");
      RouteTable.Routes.MapPageRoute("", "login", "~/Login.aspx");
      ...others
   }

   protected void Application_BeginRequest(object sender, EventArgs e)
   {
      String fullOriginalPath = Request.Url.ToString();
      //if link contains .aspx is not a rewrite
      if(fullOriginalPath.Contains(".aspx"))
      {
         return;
      }

      GetRewrites();
     
      int index = 0;
      if (fullOriginalPath.Contains("www.mysite.com"))
         index = fullOriginalPath.IndexOf('/', fullOriginalPath.IndexOf("www.mysite.com")) + 1;
      else
         index = fullOriginalPath.IndexOf('/', fullOriginalPath.IndexOf("localhost")) + 1;

      string chiave = fullOriginalPath.Substring(index).ToLower();

      //check if exists in RouteTable
      //skip first 2 element 
      for (int i = 2; i< RouteTable.Routes.Count; i++)
      {
         System.Web.Routing.Route rx = RouteTable.Routes[i] as System.Web.Routing.Route;
         if (rx.Url == chiave)
            return;
      }

      //if not exists in redirect rules it must go to the home page
      if(rewrites.Where(x=>x.Chiave == chiave).Count() == 0)
      {
         Response.Redirect("home");
         return;
      }
  }

Here the problem:

If I go to localhost:4210/home it's all ok

If I publish my application on server and I try to go at link www.mysite.com/home

I get the error The site is redirected too many times.

Can someone have an Idea of the motivation?

1

There are 1 answers

0
Martina On

The problem was that in my web.config file (on server and not locally) there was these lines for rewrite

 <rule name="home page" stopProcessing="true">
      <match url="(.*)" />
      <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
        <add input="{HTTP_HOST}{REQUEST_URI}" pattern="www.mysite./Home" />
      </conditions>
      <action type="Redirect" url="https://www.mysite." redirectType="Permanent" />
    </rule>

Commented this rule now it works PS (the site is .com and not empty but SO doesn't permit me to write it)