簡體   English   中英

如何在asp.net中使301永久重定向

[英]how to make 301 permanent redirect in asp.net

您能否告訴我,如何在asp.net中進行301永久重定向?

我已經在Global.asax文件中編寫了代碼,但是我的網絡客戶端說它無法正常工作,

我在Global.asax文件中編寫了以下代碼:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
"http://lsatfreedom.com"))
        {
            HttpContext.Current.Response.Status =
                "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location",
                Request.Url.ToString().ToLower().Replace(
                    "http://lsatfreedom.com",
                    "http://www.lsatfreedom.com"));
        } 

    }

它有用嗎? 請幫忙。

謝謝

首先嘗試查看此重定向是否在頁面加載中有效。 如果是,請嘗試使用Begin_Request。

希望這給您一些線索:

private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://www.new-url.com");
}

我認為您缺少Response.Clear()Response.End() ,請嘗試使用此方法。

例如:

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
"http://lsatfreedom.com"))
        {
           string sNewPage = Request.Url.ToString().ToLower().Replace(
                    "http://lsatfreedom.com",
                    "http://www.lsatfreedom.com");

            Response.Clear();
            Response.Status = "301 Moved Permanently";
            Response.AddHeader("Location", sNewPage);
            Response.End();
        } 
    }

我相信您缺少CompleteRequest()

因此,您的代碼應如下所示:

    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
        "http://lsatfreedom.com"))
    {
        HttpContext.Current.Response.Status =
            "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location",
            Request.Url.ToString().ToLower().Replace(
                "http://lsatfreedom.com",
                "http://www.lsatfreedom.com"));
       CompleteRequest();
    } 

如果不添加CompleteRequest,則ASP.Net會嘗試自行處理它,在這種情況下,標頭可能存在,但在開始響應和結束響應之間,狀態實際上可能會被覆蓋。 這樣可以避免實際重定向。

我將更改web.config並從此答案中添加以下規則。

將http://mydomain.com/ctrlr/act/val轉發到http://WWW.mydomain.com/ctrlr/act/val

這就是我們添加www的方式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM