Use URL Routing with Web Forms / Main ASP.NET Pages

Description and samples
Table of Contents
Description

To enable routing on common ASP.NET pages is required:

  • The configuration file for the application to register the routing assembly and to add the UrlRoutingModule class as a module;
  • A custom route handler for the route: The handler implements the IRouteHandler interface and creates an instance of the Web form;
  • The “.aspx” file that will be the actual endpoint for the request;
  • The routes that are served by the handler must be defined.
Custom handler to render page content

The route handler is an object that implements the IRouteHandler interface.
This interface defines a single method, “GetHttpHandler”, which is responsible for returning the HTTP Handler to use to generate the response, since all ASP.NET Web Form pages are HTTP Handlers.

An HTTP Handler is a class that implements the IHttpHandler interface: HTTP Handlers knows how to process an ASP.NET request and generate content in response. For more information on HTTP Handlers, see HTTP Handler description article.

 

Operations
Implementing URL Routing in ASP.NET 3.5

In the code presented next, the globalization file “global.asax” register routes, where all the virtual URLs are mapped to one or more “.aspx” distinct pages that are buit at runtime through the custom handler “pagerouteHandler”.

To be possible to manipulate the route data (i.e. URL parameters correspondent to the placeholders in the route patterns) they are explicitly added to “HttpContext.Items” collection property

Remarks

The custom handler is required on NET 3.5.

How to do it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;

namespace Training.IIS
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        public static void RegisterRoutes(RouteCollection pRoutes)
        {
            pRoutes.Clear();

            pRoutes.Add("category1", new Route(
               "training/categories/{action}/{id}", new pagerouteHandler("~/CategoriesPage.aspx"))
            );

            pRoutes.Add(
                    "category2",
                    new Route (
                            "training/categories/{action}/{id}",
                            new RouteValueDictionary {{"action","show"},{"id","all"}},
                            new pagerouteHandler("~/CategoriesPage.aspx"))
            );

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Routing;

namespace Training.IIS
{
    public partial class CategoriesPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<p><b>Url: " + Request.RawUrl + "<b></p><p>   Action: " + HttpContext.Current.Items["action"] + "</p><p>  Id: " + HttpContext.Current.Items["id"].ToString() + "<p>");
        }
    }
}
?xml version="1.0"?>
<configuration>

	<!-- Configuration for II6 and prior versions / II7 Classic mode -->
	<system.web>
		<compilation debug="true">
			<assemblies>
				<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			</assemblies>
		</compilation>

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

	</system.web>

	<!-- Configuration for II7 -->
	<system.webServer>

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

		<handlers>
			<add name="UrlRoutingHandler"
				preCondition="integratedMode"
				verb="*"
				path="UrlRouting.axd"
				type="System.Web.HttpForbiddenHandler,
				System.Web, Version=2.0.0.0,
				Culture=neutral,
				PublicKeyToken=b03f5f7f11d50a3a" />
		</handlers>

	</system.webServer>

</configuration>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.Routing;

    public class pagerouteHandler : IRouteHandler
    {
        public pagerouteHandler(string pVirtualPath)
        {
            this.VirtualPath = pVirtualPath;
        }

        public string VirtualPath { get; private set; }

        public IHttpHandler GetHttpHandler(RequestContext pRequestContext)
        {
            var _page = BuildManager.CreateInstanceFromVirtualPath
                 (VirtualPath, typeof(Page)) as IHttpHandler;

            // Transfer ROUTE DATA to be accessible in the base as HttpContext items
            foreach (var lvUrlParam in pRequestContext.RouteData.Values)
            {
                pRequestContext.HttpContext.Items[lvUrlParam.Key] = lvUrlParam.Value;
            }

            return _page;
        }
    }
Implementing URL Routing in ASP.NET 4.0

In the code presented next, the globalization file “global.asax” register routes, where all the virtual URLs are mapped to one or more “.aspx” distinct pages through the extension method “RouteCollection::MapPageRoute()”

The route data can be (i.e. URL parameters correspondent to the placeholders in the route patterns) can be explicitly manipulated through the “Page::RoutData::Values()” collection property

Remarks

The custom handler is not required on NET 4.0.

The route data parameters are integrated on the “Page” class.

The extension method “RouteCollection::MapPageRoute()” builts automatically the custom handler that was required on NET 3.5

How to do it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;

namespace Training.IIS
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        public static void RegisterRoutes(RouteCollection pRoutes)
        {
            pRoutes.Clear();

            pRoutes.MapPageRoute(
						"category1",
						"training/categories/{action}/{id}",
						"~/CategoriesPage.aspx")
            ));

            pRoutes.MapPageRoute(
						"category2",
						"training/categories/{action}/{id}",
						"~/CategoriesPage.aspx",
						true,
						new RouteValueDictionary {{"action","show"},{"id","all"}})
            );

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Routing;

namespace Training.IIS
{
    public partial class CategoriesPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<p><b>Url: " + Request.RawUrl + "<b></p><p>   Action: " + Page.RoutData["action"] + "</p><p>  Id: " + Page.RoutData["id"].ToString() + "<p>");
        }
    }