c# .net web应用程序重定向中的问题
本文关键字:问题 重定向 应用程序 net web | 更新日期: 2023-09-27 18:03:01
我编写了这个httpmodule并将其正确添加到网站,但当我运行它时,它会给我这个错误:
**页面没有正确重定向
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() { }
}
}
每个begin请求都被重定向,即使指向相同的url。在调用context.Response.Redirect()
之前,您需要检查以确保重定向是必要的。
我认为问题出在:
context.Response.Redirect(ParseAndReapply(req));
BeginRequest事件表示任何给定的新请求的创建。在每个重定向中,它都会被调用。在你的代码中,它被重定向到一个新的请求这会导致一个无限循环。试着重新考虑你的逻辑。
除了在其他答案中列出的回避问题之外,看起来您正在重定向到相对路径(www.example.com/Blog/?tag=/....)
试试http://www.example.com/Blog/?tag=/..。
在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();
}
如果ParseAndReply的参数不包含"example.com",它将无限重定向到自身。
另一个注意事项:
if (textToParse.Contains(".") && textToParse.Contains("example.com"))
是多余的。"example.com"总是包含'.'