URL重写

为什么要URL重写?

1. 有利于SEO,带参数的URL由于内容可能是动态改变的,因此带参数的URL权重较低;

2. 地址看起来更正规

HttpContext的RewritePath()实现URL重写两种方式:

每个浏览器端的请求都会在Application_BeginRequest中触发,

原地址:url="/Booklist_25.aspx";

重写后地址:url="/Booklist.aspx?categoryId=25";

1. 自定义实现IHttpModual接口的类,在Init方法中注册BeginRequest事件,在事件响应方法中截获并重写url,

   并且需要在Web.config文件中<httpModules>节点中配置。

   public class UrlRewriteModule:IHttpModual

     {

            public void Init(HttpApplication application)

            {

                    application.BeginRequest +=new EventHandler(Application_BeginRequest);

            }

            private void Application_BeginRequest(object source,EventArgs e)

            {

                     HttpApplication application = source as HttpApplication;

                     HttpContext context = application.Context;

                     Uri url = context.Request.AppRelativeCurrentExecutionFilePath;//得到当前请求的虚拟路径

                     Match match = Regex.Match(url,@"~/Booklist_(\d+)\.aspx"); //匹配

                     if(match.Success)

                    {

                          int id = Convert.ToInt32(match.Groups[1].Value); //得到类别编号

                          Context.RewritePath("/Booklist.aspx?categoryId="+id); //修改url请求,找到后台真正的页面返回

                    }

            }

     }

 

 web.cofig文件配置:注册此模块

<configuration>

  <system.web>

    <httpModules>

      <add name="UrlRewriteModule" type="UrlRewriteModule"/>

     </httpModules>

  </system.web>

</configuration>

 

2)创建Global.asax文件,在下面方法中处理:

Protected void Application_BeginRequest(object sender,EventArgs e)

{

     //此方法中截获url请求

     string url = Request.AppRelativeCurrentExecutionFilePath;// ~/Booklist_25.aspx 只有符合这种格式的才进行 url重写,否则所有请求的页面都被重写了。此方法会给传过来的url请求前面加上~

     Match match = Regex.Match(url,@"~/Booklist_(\d+)\.aspx"); //匹配

     if(match.Success)

     {

          int id = Convert.ToInt32(match.Groups[1].Value); //得到类别编号

 

          Context.RewritePath("/Booklist.aspx?categoryId="+id); //修改url请求,找到后台真正的页面返回

     }

}

 ------------------------------------

Rewrite、Redirect、Server.Transfer和Server.Execute之间的区别:

Rewrite(重写):可以把页面请求发给其他页面进行处理,地址栏一直没有变化,

Response.Redirect(重定向):返回给客户端浏览器一个302状态码和新的页面地址,然后浏览器会再次向新页面发送请求,这个过程浏览器和服务器交互两次,地址栏发生变化。

Server.Transfer:服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器,这个过程中浏览器和Web服务器之间只经过了一次交互。

Server.Execute方法允许当前的ASPX页面执行一个同一Web服务器上的指定ASPX页面,当指定的ASPX页面执行完毕,控制流程重新返回原页面发出Server.Execute调用的位置。   
  这种页面导航方式类似于针对ASPX页面的一次函数调用,被调用的页面能够访问发出调用页面的表单数据和查询字符串集合,所以要把被调用页面Page指令的EnableViewStateMac属性设置成False。   
  默认情况下,被调用页面的输出追加到当前应答流。但是,Server.Execute方法有一个重载的方法,允许通过一个TextWriter对象(或者它的子对象,例如StringWriter对象)获取被调用页面的输出,而不是直接追加到输出流,这样,在原始页面中可以方便地调整被调用页面输出结果的位置。

Server.Transfer和Server.Execute不可以转向外部网站,而Response.Redirect可以。

 

 

原文地址:https://www.cnblogs.com/chay1227/p/2694561.html