How to 301 redirect in ASP.NET 4.0?

后端 未结 5 633
再見小時候
再見小時候 2020-12-16 15:59

I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.

I

5条回答
  •  鱼传尺愫
    2020-12-16 16:33

    if you didn't know what is application domain name ,use something like this

    protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost"))return;
            var leftPartOfUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToLower();
            if (leftPartOfUrl.StartsWith("http") && leftPartOfUrl.Split('.').Length == 1)
            {
                var fullUrl = HttpContext.Current.Request.Url.ToString();
                HttpContext.Current.Response.Status = "301 Moved Permanently";
                HttpContext.Current.Response.StatusCode = 301;
                HttpContext.Current.Response.AddHeader("Location", fullUrl.Insert(fullUrl.IndexOf("://", StringComparison.Ordinal) + 3, "www."));
                HttpContext.Current.Response.End();
            }
        }
    

提交回复
热议问题