详细讲解ASP.NET 3.5URL路由(URL Routing)总结
下面文章详细分析讲解在.NET3.5框架中路由这个功能的特点及使用的知识点,URL Routing是非常重要的一块技术体系,笔者将URL Routing的知识进行梳理后得出本文,旨在同大家分享,希望能够起到抛砖引玉的作用。
1. 什么是URL Routing?
所谓URL Routing(URL路由),指的是在Web中,URL不再是文件目录中的一个文件,而是一个说明有关URL路由的字符串,开发者可以自定义该字符串的格式。
2. 为什么要使用URL Routing?
主要目的:URL更加的友好,方便web使用者理解相关页面的功能。至于其它目的嘛,这个就太广了,甚至可以在使用中慢慢挖掘它的用处。
3. URL Routing是MVC才有的吗?
URL Routing的程序集System.Web.Routing位于.NET框架3.5的SP1版本中,是与ASP.NET MVC框架分离的,因此,在WebForm项目中也可以使用路由。
4. 如何在WebForm中使用路由?
要在WebForm中使用路由,只需要完成4个步骤即可:
Ø 添加对System.Web.Routing的引用;
Ø 创建一个实现IRouteHandler接口的类,如WebFormRouteHandler类;
Ø 在Global.asax.cs中将我们创建的RouteHandler进行全局应用配置;
Ø Web.config中配置System.Web.Routing的引用
using System.Web.Routing;
using System.Web.Compilation;
using System.Web.UI;
namespace RoutingInWebForm
{
public class WebFormRouteHandler:IRouteHandler
{
public string VirtualPath{ get;private set; }
public WebFormRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
}
using System.Web.Routing;
namespace RoutingInWebForm
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add("Named", new Route("foo/bar", new WebFormRouteHandler("~/WebForm1.aspx")));
routes.Add("Number", new Route("one/two/three", new WebFormRouteHandler("~/WebForm2.aspx")));
}
}
}
Web.config中配置System.Web.Routing的引用的代码如下:
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
<!--[endif]-->