Loading

认识 ASP.NET 3.5 MVC 路由 在WebForm项目中使用路由

路由程序集System.Web.Routing位于.NET框架3.5的SP1版本中,是与ASP.NET3.5 MVC分离的,所以在传统的Web Form项目中也可以使用路由。

ASP.NET 路由使您可以处理未映射到 Web 应用程序中物理文件的 URL 请求。默认情况下,在动态数据或 MVC 框架的一个 ASP.NET 应用程序中启用 ASP.NET 路由,而不在 ASP.NET 网站项目中启用路由。

因此,若要在 ASP.NET 网站中使用路由,必须采取措施来启用。

要实现在WebForm中使用路由,首先需要创建实现IRouteHandler接口的WebFormRouteHandler类,然后在全局应用程序类中配置路由的映射就可以了。

WebFormRouteHandler代码如下:

using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;
namespace MVCWebApplication1
{
    public class WebFormRouteHanlder : IRouteHandler
    {
        public string VirtualPath { get; private set; }
        public WebFormRouteHanlder(string virtualPah)
        {
            VirtualPath = virtualPah;
        }
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            var page = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
            return page;
        }
    }
}
在Global.asax中配置路由:
using System;
using System.Web.Routing;
namespace MVCWebApplication1
{
    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 WebFormRouteHanlder("~/forms/blech.aspx")));
            routes.Add("Number", new Route("one/two/three", new WebFormRouteHanlder("~/forms/haha.aspx")));
        }
    }
}

 

还需要在Web.config中配置System.Web.Routing的引用!

      <httpModules>
        <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </httpModules>

 

运行,访问http://localhost:5598/foo/bar 。OK~~~~

参考:MSDN,MVC架构与实战  地址:如何:MSDN帮助 对 Web 窗体使用路由

posted @ 2009-10-13 14:29  Dhoopu  阅读(681)  评论(0编辑  收藏  举报