服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET实现301重定向方法

ASP.NET实现301重定向方法

2020-05-26 14:12asp.net教程网 ASP.NET教程

我们给大家整理了关于ASP.NET中实现301重定向的方法以及小技巧总结,有兴趣的朋友可以操作试试。

?
1
<span style="font-family:'宋体';font-size:10.5pt;"></span>

关于百度等搜索引擎对于是否带"www"前缀的域名的识别问题:即搜索引擎会将www.abc.com和abc.com识别为不同的两个域名,这样做的后果就是分散了对网站的关注度,不利于网站的宣传和推广。

仅仅是通过Response.Redirect方法来重定向该连接,虽然可以将连接进行重定向,但是无法解决搜索引擎的识别分散问题的;此问题可通过301重定向来进行解决,具体在ASP.NET中可通过如下方法来处理:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private void CheckTopDomainName(HttpContext context)
     {
       Uri url = context.Request.Url;
       string host = url.Host.ToLower();
  
       int count = host.Split('.').Length;
       bool doubleDomainName = host.EndsWith(".com.cn", StringComparison.CurrentCultureIgnoreCase) ||
         host.EndsWith(".net.cn", StringComparison.CurrentCultureIgnoreCase) ||
         host.EndsWith(".gov.cn", StringComparison.CurrentCultureIgnoreCase) ||
         host.EndsWith(".org.cn", StringComparison.CurrentCultureIgnoreCase);
  
       if (count == 2 || (count == 3 && doubleDomainName))
       {
         context.Response.Status = "301 Moved Permanently";
         // 避免替换掉后面的参数中的域名
         context.Response.AddHeader(
           "Location"
           url.AbsoluteUri.Replace(
             string.Format("http://{0}", host), 
             string.Format("http://www.{0}", host)
             )
           );
       }

更多关于ASP.NET301实现的方法实例:

因为IIS设置301需要在服务器中配置很麻烦,所以ME选择了在程序中实现。
程序中实现有个缺点就是执行效率没有在IIS服务器中速度快。

当然了,这里说的只是适合动态网站的,如果都是.html静态文件就飘过吧!

好了还是直接上代码吧:

网页首页文件index.aspx后台代码

?
1
2
3
4
5
6
7
8
9
//判断是否是www.开头,如果不是301调整到www.域名
if (!System.Web.HttpContext.Current.Request.Url.ToString().StartsWith("http://www."))
{
   //301 重定向到 /目录下          
   HttpContext.Current.Response.StatusCode = 301;
   HttpContext.Current.Response.Status = "301 Moved Permanently";
   HttpContext.Current.Response.AddHeader("Location", "http://www.fuwa.org/");
   HttpContext.Current.Response.End();
}

这里因为是我的独立站点,所以直接写www.了。如果是二级域名就需要根据需求自己修过了。

栏目页/内容页代码:

//如果url结尾不是以/符号结尾的,同样301到末尾增加/符号。

?
1
2
3
4
5
6
7
8
if (!System.Web.HttpContext.Current.Request.RawUrl.EndsWith("/"))
{
     //301 重定向到 /目录下
     HttpContext.Current.Response.StatusCode = 301;
     HttpContext.Current.Response.Status = "301 Moved Permanently";
     HttpContext.Current.Response.AddHeader("Location", System.Web.HttpContext.Current.Request.RawUrl + "/");       
     HttpContext.Current.Response.End();
}

 

延伸 · 阅读

精彩推荐