2011-07-20 42 views
1

我编写该HTTP模块和正确添加到它的网站,但它给我这个错误,当我运行它:问题在C#.NET Web应用程序重定向

**页面没有正确重定向

Firefox已经检测到服务器重定向此地址的 请求的方式,将永远不会完成**

using System; 
    using System.Web; 
    using System.Net; 
    using System.Text; 
    using System.IO; 

    namespace CommonRewriter 
    { 
     public class ParseUrl : IHttpModule 
     { 
      public ParseUrl() 
      { 

      } 

      public String ModuleName 
      { 
       get { return "CommonRewriter"; } 
      } 

      public void Init(HttpApplication application) 
      { 
       application.BeginRequest += new EventHandler(application_BeginRequest); 
       application.EndRequest += new EventHandler(application_EndRequest); 
      } 


      private string ParseAndReapply(string textToParse) 
      { 
       string final = null; 

       if (textToParse.Contains(".") && textToParse.Contains("example.com")) 
       { 
        string[] splitter = textToParse.Split('.'); 
        if (splitter[0].ToLower() != "www" &&(splitter[2].ToLower()).Contains("blog")) 
        { 
         final = ("www.example.com/Blog/?tag=/" + splitter[0]); 
        } 
        else { final = textToParse; } 
       } 
       else { final = textToParse; } 

       return final; 
      } 

      void application_BeginRequest(object sender, EventArgs e) 
      { 
       HttpApplication application = (HttpApplication)sender; 
       HttpContext context = application.Context; 

       string req = context.Request.FilePath; 
       context.Response.Redirect(ParseAndReapply(req)); 
       context.Response.End(); 
      } 


      void application_EndRequest(object sender, EventArgs e) 
      { 

      } 

      public void Dispose() { } 

     } 
    } 

回答

0

我认为这个问题是:

context.Response.Redirect(ParseAndReapply(req)); 

BeginRequest事件表示创建任何给定的新请求。所以在每个重定向中,它都会被调用。在你的代码中,它被重定向到一个导致无限循环的新请求。试着重新考虑你的逻辑。

1

每个开始请求都会重定向,即使是相同的网址。在致电context.Response.Redirect()之前,您需要进行检查以确保重定向是必需的。

0

application_BeginRequest要重定向通过context.Response.Redirect(ParseAndReapply(req));

申请您应该检查是否重定向前一个条件为真,如

string req = context.Request.FilePath; 
if (req.Contains(".") && req.Contains("example.com")) 
{ 
    context.Response.Redirect(ParseAndReapply(req)) 
    context.Response.End(); 
} 
0

如果ParseAndReply的参数不包含“example.com”,它将无限地重定向到它本身。

一个其他说明:

if (textToParse.Contains(".") && textToParse.Contains("example.com")) 

是多余的。 “example.com”将始终包含“。”

+0

感谢您指出。原来它只是'textToParse.Contains(“。”)'我稍后添加了“example.com”部分 – user796762

+0

我正在使用的站点是一个具有ip地址而不是域名的开发站点。即时通讯使用主机文件将IP更改为可用域。 string req = context.Request.FilePath;'是否可以返回一个用于评估的IP地址而不是文本域名。 – user796762

+0

主机名应该不重要。 Filepath返回URL的文件和路径部分,不包含主机名或任何查询字符串值。您的重定向条件触发的唯一方法是如果您有像“http://somesite.com/example.com/file.aspx?arg=val1&arg2=val2”这样的URL“ ”FilePath将返回“/example.com/file .aspx“。 –

相关问题