2010-01-21 22 views
5

tôi có thể sử dụng bắt đầu yêu cầu của Global.asax để chuyển hướng tất cả mọi thứ,Toàn Cầu 301 từ miền để www.domain

từ mydomain.domain-www.mydomain.domain?

Nếu điều này đúng, tôi có thể làm như thế nào?

Trả lời

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

Xin chào, tôi thấy rằng các handler PreRequest không tồn tại trong global.asax vì vậy tôi thêm nó như bạn đề xuất. Nhưng sự kiện này không được kích hoạt trong chế độ gỡ lỗi ... Tôi đang làm điều gì khác sai ở đây? – OrElse

+0

Nó có kích hoạt khi bạn thay đổi 'PreRequestHandlerExecute' thành' BeginRequest'? –

+0

Yeap! BeginRequest kích hoạt trong mọi yêu cầu – OrElse

9

Một vài thay đổi nhỏ để câu trả lời của Jan đã nhận nó làm việc cho tôi:

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(); 
    } 
} 

Thay đổi là để sử dụng các sự kiện BeginRequest và thiết CURRENTURL để HttpContext.Current.Request.Url thay vì HttpContext .Current.Request.Path. Xem:

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

Các vấn đề liên quan