Default Route in ASP.NET 4 URL Routing

21. July 2010 17:50


I was playing around trying to learn URL Routing in ASP.NET 4. I wanted to find a way to have a wildcard or default route to handle any page ending in .ASPX.

I originally came across this post on stackoverflow

http://stackoverflow.com/questions/2704338/asp-net-4-0-web-forms-routing-default-wildcard-route

However, it didn't seem to work (or at least I couldn't get it to work properly).

So I took the concept of that post and created a default route handler that seems to be working OK.

Note: I'm just now learning this, so if you have a better reference for those reading this please leave a link in the comments or leave a suggestion for a better way :)

Here was the goal I was trying to accomplish

http://localhost:18849/Default -> http://localhost/Default.aspx
http://localhost:18849/About -> http://localhost/About.aspx
http://localhost:18849/Contact -> http://localhost/Contact.aspx
http://localhost:18849/Dir1/Page1 -> http://localhost/Dir1/Page1.aspx

Here is a screenshot of my test solution in Visual Studio 2010

 

 

Now for what I did.

First thing I did was add a reference to System.Web.Routing

Next, you need to add code to the global.asax file to register your routes. My resulting Global.asax.cs page looked like this

void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RegisterRoutes(RouteTable.Routes);

        }

        void RegisterRoutes(RouteCollection routes)
        {
            routes.Ignore("{resource}.axd/{*pathInfo}");
                     
            //TODO: Rest of known routes here

            //Default route
            routes.Add(new Route("{*value}", new DefaultRouteHandler()));

        }



You'll notice a class called DefaultRouteHandler().  This is class I created to handle the route.

So you'll want to add a new class to your solution called DefaultRouteHandler.cs.  This class will implement the Interface IHttpHandler

public class DefaultRouteHandler: IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            var pageUrl = requestContext.HttpContext.Request.Path + ".aspx";
            pageUrl = string.Format("~{0}", pageUrl);

            var page = new object();

            try
            {
                page = BuildManager.CreateInstanceFromVirtualPath(pageUrl, typeof(Page));

                if (page != null)
                {
                    //Set the forms postback url to the route
                    var webForm = page as Page;
                    if (webForm != null)
                        webForm.Load += delegate
                        {
                            webForm.Form.Action =
                            requestContext.HttpContext.Request.RawUrl;
                        };
                }

                return page as IHttpHandler;
            }
            catch (Exception ex)
            {
                page = BuildManager.CreateInstanceFromVirtualPath("~/NotFound.aspx", typeof(Page));

                return page as IHttpHandler;
            }
            
        }
    }



You'll see in the code above I grab the Path of the request and append .aspx to it. This is because if someone types in http://localhost:18849/Contact we

need to add the .aspx to it so we can use it in the CreateInstanceFromVirtualPath method.

I wrapped this in a try-catch method because if the CreateInstanceFromVirtualPath failed, then we can redirect to our basic NotFound.aspx page.


With this code I have accomplished what I set out to do by having a route for my .aspx pages that don't do anything special.


Other References:

ASP.NET.4GuysFromRolla.com: URL Routing in ASP.NET 4.0

http://www.4guysfromrolla.com/articles/012710-1.aspx


Walkthrough: Using ASP.NET Routing in a Web Forms Application

http://msdn.microsoft.com/en-us/library/dd329551.aspx

How to: Define Routes for Web Forms Applications

http://msdn.microsoft.com/en-us/library/cc668177.aspx

Tags:

ASP.NET

blog comments powered by Disqus



My Random Thought

I think the OCW is a great thing to have available to those who are in school, just finished school or just want to educate themself

http://ocwconsortium.org/

John On Twitter

Discounts