什么是URL Routing?

所谓URL RoutingURL路由),指的是在Web中,URL指向的不再是某个物理文件,而是一个说明有关URL路由的字符串,开发者可以自定义该字符串的格式。在默认情况下,URL Routing在ASP.NET应用程序中是可以直接使用的,但在ASP.NET站点上,需要做一些配置才能使用。

 

为什么要使用URL Routing?

在使用URL Routing前,我们的URL可能是http://www.mysite.com/profile.aspx?userid=1,使用URL Routing后,我们的URL可以变成http://www.mysite.com/profile/1。修改后的URL更加友好,更有利于SEO。至于其它目的嘛,在使用过程中再慢慢挖掘吧。

 

URL Routing只能在MVC中才能使用吗?

路由程序集(System.Web.Routing.dll)在.NET Framework V3.5 sp1中就包含了,而MVC是在之后才发布的。因此不能说URL Routing只能在MVC中才能使用。不过在MVC中增加了Routing在一些扩展方法(包含在System.Web.MvcRouteCollectionExtemsion类中),使用起来更加方便。


下面简单介绍下如何在Web Form中使用URL Routing。

1. 添加对程序集System.Web.Abstractions.dll,System.Web.Routing.dll的引用

 

2. 添加一个IRouteHandler的实现类CustomRouteHanlder

 1 using System.Web;
 2 using System.Web.Compilation;
 3 using System.Web.Routing;
 4 using System.Web.UI;
 5 
 6 public class CustomRouteHandler : IRouteHandler
 7 {
 8     public string VirtualPath
 9     {
10         get;
11         private set;
12     }
13 
14     public CustomRouteHandler(string virtualPath)
15     {
16         this.VirtualPath = virtualPath;
17     }
18 
19     #region IRouteHandler Members
20 
21     public IHttpHandler GetHttpHandler(RequestContext requestContext)
22     {
23         var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
24         return page;
25     }
26 
27     #endregion
28 }

相关文章: