ASP.NET - Routing

This is a walkthrough for ASP.NET routing. The concept of routing is very interesting, it allows you to take this URL:

http://mysite.com/articles.aspx?ArticleID=HowToCodeRouting&Theme=Orange

to this:

http://mysite.com/articles/HowToCodeRouting/Orange

The overall effect is more searchable and more self explanitory to look at.

Our code example is very short, just enouth to get you up to speed and coding... quickly.

Edit 2/21/2015: the two 'Ignore' lines were added to avoid this error:

JavaScript critical error at line 4, column 1 in http://localhost:55362/WebResource.asx?... Syntax error

First, add two methods to the Global.asax file

    Sub Application_Start(ByVal sender As ObjectByVal e As EventArgs)
        ' Code that runs on application startup

        RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}")

        RouteTable.Routes.Ignore("{resource}.ashx/{*pathInfo}")


        RegisterRoutes(RouteTable.Routes)
    End Sub

 

    Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
        routes.MapPageRoute("",
                            "Ministries/{ministryName}",
                            "~/ministries.aspx",
                            True,
                            New RouteValueDictionary(New With {.ministryName = "ministriesHome"}))
    End Sub

and in the target page (in this case 'Ministries.aspx')

    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
        Dim strMinistry = Convert.ToString(Page.RouteData.Values("ministryName"))
 
    End Sub

First, we register a route for "Ministries/{ministryName}" and we send it to "~/ministries.aspx".  We also tell the route that if no 'ministryName' is provided, the default will be "ministriesHome"

Next we retrieve the variable in the target page.

That's all there is to it.

 

 

 

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences