2010-01-21 132 views

回答

4
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e) 
{ 
    string currentUrl = HttpContext.Current.Request.Path.ToLower(); 
    if(currentUrl.StartsWith("http://mydomain")) 
    { 
    Response.Status = "301 Moved Permanently"; 
    Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain")); 
    Response.End(); 
    } 
} 
+0

您好,我发现PreRequest处理器并没有在Global.asax存在所以我说这是你提议。但事件不是在调试模式下被解雇的......我在这里做了其他的错误? – OrElse 2010-01-22 09:04:10

+0

当你将'PreRequestHandlerExecute'改成'BeginRequest'时它会触发吗? – 2010-01-22 09:51:23

+0

Yeap! BeginRequest在每个请求中触发 – OrElse 2010-01-22 11:00:19

9

A到一月的回答微小的改动得到它的工作对我来说:

protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
    string currentUrl = HttpContext.Current.Request.Url.ToString().ToLower(); 
    if (currentUrl.StartsWith("http://mydomain")) 
    { 
     Response.Status = "301 Moved Permanently"; 
     Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain")); 
     Response.End(); 
    } 
} 

变化是使用BeginRequest事件,并CURRENTURL设置为HttpContext.Current.Request.Url代替的HttpContext的.Current.Request.Path。请参阅:

http://www.mycsharpcorner.com/Post.aspx?postID=40