当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET实现301重定向方法

ASP.NET实现301重定向方法

2018年04月28日  | 移动技术网IT编程  | 我要评论

美女跳楼记,吴桂存,日将部署航母杀手

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

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

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

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后台代码

//判断是否是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.qinquan.org/"); 
   httpcontext.current.response.end(); 
}

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

栏目页/内容页代码:

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

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网