Chris Cavanagh’s Blog

ASP.NET Routing… Goodbye URL rewriting?

March 11, 2008 · 143 Comments

UPDATES:
>
Added some detail about routing with IIS7.  See end of post :)
> .NET 3.5 SP1 includes ASP.NET Routing as part of the framework.  If you’re using ASP.NET AJAX (or anything else that uses resource handlers like WebResource.axd) be sure to check out this page.  Without it you’ll find all resource requests go through to your page handler! :)
> You can find a sample project and more details here.
> Be sure to check out Phil Haack’s post covering some of the security implications of this.  I’ve also added a related comment to the end of this post :)
> Added a new post that might help you resolve issues with relative file paths when using routes.  Check it out here.
> Added a VB.NET sample project here!  Thinking I need a new post to get all these updates under control ;)
> Added some SiteMap support here.
> Article on routing by Satheesh Babu here.
> ASP.NET 4.0 makes WebForm routing even easier; see Scott Guthrie’s post here.

The System.Web.Routing assembly introduced with .NET 3.5 SP1 (originally part of ASP.NET MVC) brings some interesting stuff for "traditional" ASP.NET developers.  Check out this post by Phil Haack (and be sure to keep up with his upcoming posts that will go into more detail).

One of the obvious uses for the new routing mechanism is as a "clean" alternative to URL rewriting (and possibly custom VirtualPathProviders for simple scenarios) for traditional / postback-based ASP.NET sites.  After a little experimentation I found some minimal steps that work pretty well:

  • Create a custom IRouteHandler that instantiates your pages
  • Register new Routes associated with your IRouteHandler
  • That’s it!

The IRouteHandler implementation can be as simple or elaborate as you like.  Just implement the GetHttpHandler method and return a new instance of an ASP.NET page (if you want to use an ASPX you can instantiate it with BuildManager.CreateInstanceFromVirtualPath).

Here’s a very simple IRouteHandler implementation that instantiates a single page (compiled or ASPX) for any request sent to it:

public class WebFormRouteHandler<T> : IRouteHandler where T : IHttpHandler, new()
{
    public string VirtualPath { get; set; }

    public WebFormRouteHandler( string virtualPath )
    {
        this.VirtualPath = virtualPath;
    }

    #region IRouteHandler Members

    public IHttpHandler GetHttpHandler( RequestContext requestContext )
    {
        return ( VirtualPath != null )
            ? (IHttpHandler)BuildManager.CreateInstanceFromVirtualPath( VirtualPath, typeof( T ) )
            : new T();
    }

    #endregion
}

This example could be useful in a site with a single ASPX that hosts multiple ASCXs as its "pages" (maybe one that uses the inbuilt SiteMap as a mapping mechanism between public URLs and ASCXs).  For more traditional sites, your GetHttpHandler would return separate page instances based on the RequestContext it’s provided with (RequestContext includes the routing details extracted from the URL; MVC would create a Controller at this point).

Routes are usually registered in the Application_Start handler in Global.asax.  Here’s a simple example based on the "single ASPX / multiple ASCX" approach that passes several routes to a single page (MyPage.aspx):

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

public static void RegisterRoutes( RouteCollection routes )
{
    // Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable
    //       automatic support on IIS6 and IIS7 classic mode

    var routeHandler = new WebFormRouteHandler<Page>( "~/MyPage.aspx" );

    routes.Add( new Route( "{page}", routeHandler ) );
    routes.Add( new Route( "AccountServices/{page}", routeHandler ) );
    routes.Add( new Route( "Default.aspx", routeHandler ) );
}

Phil Haack has a post that covers some security implications of this approach.  Like Phil suggests, the ‘insecure’ behavior might be exactly what you want.  You could prevent direct URL access to your ASPX’s (using ASP.NET’s existing mechanisms) and consider them just resources to be used by your IRouteHandler.

Also note that Phil includes a mechanism for passing the RequestContext to your page (just define and implement the IRoutablePage interface).

Routing in IIS6

By default IIS6 only passes certain requests to ASP.NET (.ASPX, .ASMX. ASHX etc).  To allow the routing mechanism to handle your requests you need to set up “Wildcard Application Mapping” for your application.  This causes ALL requests to your site (even static file requests) to go through ASP.NET.  This isn’t as bad as it sounds, but if you’re wanting to squeeze every last drop of performance from your app, IIS7 might be a better option.

You can find details on setting up Wildcard Application Mapping here on TechNet.

Routing in IIS7

To use all this goodness in IIS7, there are a couple of extra steps you need to take (instead of the "wildcard mapping" needed in IIS6):

  • Derive a concrete class from UrlRoutingHandler.  Something like this:
    /// <summary>
    /// Simple UrlRoutingHandler implementation
    /// </summary>
    public class RoutingHandler : UrlRoutingHandler
    {
        protected override void VerifyAndProcessRequest( IHttpHandler httpHandler, HttpContextBase httpContext )
        {
        }
    }
    
  • In web.config, under <modules> inside <system.webServer>, add this:
    <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  • Also under <modules> you’ll need to add a new attribute if you want Session state to work:
    <modules runAllManagedModulesForAllRequests="true">
  • Finally, under <handlers> (inside <system.webServer> again), add a reference to the RoutingHandler we just defined (remember to change the SimpleRoutingTest namespace and assembly name to your own):
    <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="SimpleRoutingTest.RoutingHandler, SimpleRoutingTest"/>

That should be all you need :)

Hope this helps!

kick it

Categories: .NET

143 responses so far ↓

  • Haacked // March 11, 2008 at 11:11 pm | Reply

    Great stuff! I posted my own implementation of this I’ve been working on. One thing to be aware of is it is possible to have multiple routes route to the same page. This could get around url auth on accident if you’re not careful.

  • Using Routing With WebForms // March 12, 2008 at 12:55 pm | Reply

    [...] of this for a while now based on early access to the bits. Even so, Chris Cavanagh impressively beats me to the punch in blogging his own implementation of routing for Web Forms. [...]

  • mrsvierkant // April 10, 2008 at 7:28 am | Reply

    I think I’m better off sticking with Sesame Street, LOL! :D

  • System.Web.Routing with WebForms sample « Chris Cavanagh’s Blog // April 25, 2008 at 4:29 pm | Reply

    [...] Comments Since my earlier post on using the System.Web.Routing assembly with traditional WebForms (here), I’ve had some requests for a sample project to show it in action.  You can get the [...]

  • dmitry39 // May 16, 2008 at 7:25 am | Reply

    thx, great stuff. First result in google for request “System.Web.Routing”. It’s that what i need.

    Regards from Russia :)

  • Mike Ormond's Blog : ASP.NET Routing and Authorization // June 21, 2008 at 9:03 am | Reply

    [...] Chris and Phil got there before me so I recommend reading those posts but essentially we would add an additional check as part of the route handler that checks whether the current user is authorised to view the requested path by calling UrlAuthorizationModule.CheckUrlAccessForPrincipal(). Thus, my code that I originally posted back here could be modified along the following lines: [...]

  • Net framework programmer // July 23, 2008 at 1:21 am | Reply

    We are using System.Web.Routing.dll as

    for example we route to following url’s:

    {CustomerCity}/News/
    (site url: ‘http://localhost:1979/Lazurit/Kaliningrad/News/’)

    {CustomerCity}/News/{NewsItem}/
    (site url: ‘http://localhost:1979/Lazurit/Kaliningrad/News/Lazurit1in3/’)

    virtual path of site: /Lazurit

    it works great. But how we can route to root url. When we try to route
    (“/” or “”) it does not works. We need to route to
    ‘http://localhost:1979/Lazurit/’ (it is a root url) We need to
    determine user city by ip address. After that we will redirect user to
    ‘http://localhost:1979/Lazurit/UserCity’. Is it real to create route
    for ‘http://localhost:1979/Lazurit/’? We are creating CMS system for
    it. Our main page is located in ‘Pages’ folder and has name
    ‘Main.aspx’. We need to create route ‘http://localhost:1979/Lazurit/’
    to ‘http://localhost:1979/Lazurit/Pages/Main.aspx’.

    We are using IIS 6 and asp.net 3.5 sp1

  • Using System.Web.Routing with Castle MonoRail at ILM Community Blog // August 11, 2008 at 3:38 pm | Reply

    [...] folks have already posted about using System.Web.Routing with standard ASP.NET WebForms, and I’d like to extend [...]

  • Chris Cavanagh // August 28, 2008 at 9:35 pm | Reply

    “Net Framework programmer” / progblog – Sorry I missed your post until now :( Are you still having problems with the routing or did you get it figured out?

  • Just Another Coder » Blog Archive » URL Routing, ReportViewer and Site Map Navigation // September 3, 2008 at 12:01 am | Reply

    [...] of ASP.Net MVC fame). It's already been covered well—read about URL routing here, how to implement it for web forms, and this too. Naturally I found a nail to match my new URL Routing [...]

  • Net Framework programmer // September 4, 2008 at 7:01 am | Reply

    thx for reply Chris. We have found solution. :)

  • Parthasarathy // September 26, 2008 at 12:38 am | Reply

    how can i implement asp.net routing in my WCF service? is it possible?

  • Chris Cavanagh // September 26, 2008 at 9:32 am | Reply

    Parthasarathy – Could you give an example of what you’re hoping to achieve?

    There’s an overview of some 3.5 SP1 WCF changes here: https://www.gazitt.com/blog/PermaLink,guid,dd5a7066-d288-48ef-91a8-af895fecbe8c.aspx. There’s improved REST support, but I’m not sure if that helps you or not :)

  • Ronny // September 27, 2008 at 4:17 am | Reply

    Hi Chris,
    Thanks for the great sample ;-)

    I havent been doing much asp.net for some time and now I’m about to “re-do” my old 2.0 url rewriting stuff and that lead me here.

    I have one slight off-topic thing that I am currious about: I noticed that your sample project is not a “standard” web site project – any paticular reason for that?

    Cheers,
    Ronny

  • Chris Cavanagh // September 27, 2008 at 5:18 pm | Reply

    Ronny – It’s been a while since I published it; what’s not standard about it? (would be surprised if it wasn’t just a web site project, but it’s not unknown for me to be wrong :) )

  • Ronny // September 27, 2008 at 7:27 pm | Reply

    It looks like it has been added as an “ASP.NET Web Application”, what I’ve normally done is to add a “new website” to a solution.

    The difference that I can see so far is that with a “normal website” code is auto compiled and with a “web application” it is not.

    The way I noticed this was I was not able to add the Global.asax.cs class to the root of my web site (you know so it is nested with the Global.asax file) – also namespaces are not used for pages in a “normal website”.

    I guess the differences are subtle, but I was just currious ;-) Maybe I’ve been away for a long time and this was somehow the “new” way of doing things.

    Sorry for being a little long-winded and thanks for you reply.

  • Ronny // September 27, 2008 at 7:33 pm | Reply

    I just did a quick search on this, I guess I just have a bad memory hehe

    This was introduced with VS2005 at some point, I found a post at Scott’s blog describing it here: http://weblogs.asp.net/scottgu/archive/2005/12/07/432630.aspx

  • Chris Cavanagh // September 27, 2008 at 8:42 pm | Reply

    Ronny – Web App Projects basically just re-introduced VS.NET/2003’s ASP.NET projects into VS2005 (Web Site Projects weren’t a great option for migrated projects back then). Still, I’m surprised I didn’t make this a Web Site Project :)

    You’ll probably find it cleaner to create a new web site project and just take ideas / snippets from the sample… :)

  • prabhjot singh // October 17, 2008 at 8:26 am | Reply

    i am working on a concept of making URL routing work in the project which i converted from VS2005
    to VS2008. Firstly i have made all the required changes in the global.asax file and the site root as well. The data is going in the route table but the page is not getting displayed in the browser with the mapped URL. It says “cannot locate the following page”, and secondly it is also not loading the global.asax file. what should i do?

  • Chris Cavanagh // October 17, 2008 at 9:59 am | Reply

    Prabhjot – What type of project did it convert to? (specifically, web site project or web app project). Also, are you testing/debugging in IIS or VS’s webserver? If you prefer, you can mail me some files and I’ll take a closer look :)

    You could try creating a new project in VS2008 (or use my sample) to test / prove the concepts, and then compare that directly with your own [converted] project. I often find that’s the easiest way to diagnose stuff like this.

    Hope this helps!

  • prabhjot singh // October 17, 2008 at 10:13 pm | Reply

    sir, it got converted to a website project and i am testing and debugging in VS’s webserver.

    Thanks a lot sir

  • Chris Cavanagh // October 18, 2008 at 4:30 pm | Reply

    Prabhjot – I’ve updated my sample project here: http://chriscavanagh.wordpress.com/2008/10/18/aspnet-routing-revisited-again/ (source is also available on CodePlex).

    Could you confirm the appropriate web.config settings are in your project? (compare to my sample code). It needs to register a couple of things for the routing handler to catch requests.

  • shikha // October 20, 2008 at 7:04 am | Reply

    hello
    thanks for the sample project.it was helpful.
    But according to your sample code you have given
    Search page:
    But what if i want to give dynamic value links like
    hello
    how the pathh is going to map

    Thanks

  • shikha // October 20, 2008 at 7:05 am | Reply

    hello
    thanks for the sample project.it was helpful.
    But according to your sample code you have given
    Search page:<activelink…etc
    But what if i want to give dynamic value links in anchor tag
    how the pathh is going to map

    Thanks

  • Chris Cavanagh // October 20, 2008 at 1:02 pm | Reply

    shikha – Could you give me a bit more detail about what you’re wanting to achieve?

    The RoutablePage base class in my sample includes a GetVirtualPath helper method. It allows you to dynamically construct URLs based on the currently defined routes (either using a specific named route, or a “best match”). You can see an example of its use in http://www.codeplex.com/ASPNET35Routing/SourceControl/FileView.aspx?itemId=204614&changeSetId=12901 .

    The last argument to GetVirtualPath is an anonymous type containing key/value pairs to subtitute in the URL (internally it calls http://msdn.microsoft.com/en-us/library/cc679806.aspx ).

    Let me know if this helps :) (or not; I can always add more detail).

  • shikha // October 21, 2008 at 5:03 am | Reply

    hello

    i have implimented the url routing for dynamic and ststic also
    .But the javascript and css which are present on the
    different folders of same project .and called on the aspx pages are not calling these javascript and css.
    could you plz help me out with this
    Thanks

  • Chris Cavanagh // October 21, 2008 at 1:18 pm | Reply

    shikha – This issue is a result of the way browsers resolve relative paths. By default they’re based on the URL of the requested page. In the case of routing, the path the browser requests [for a page] doesn’t necessarily correspond to the physical location of the page on the server. When the browser tries to request the css/js resources based on this URL, it won’t be able to find them…

    There are a few ways to solve this:

    1) Include your CSS content in your theme folder (App_Themes/MyTheme). ASP.NET should automatically add the relevant references.
    2) Include all your Javascript (and CSS if not using themes) in a Master Page in the application root. Paths to Javascript and CSS will be relative to the Master Page location.
    3) Set the HTML ‘BASE’ element in your page (http://www.w3.org/TR/REC-html40/struct/links.html#h-12.4). It’s possible to set this dynamically with a little codebehind (or embedded code).
    4) Try adding a route (in Global.asax) for .js and .css files and see if there’s a programmatic way to serve them up (not sure if this is possible; I’ll take a look).

    Hope this helps (hopefully one of these ideas will work! :) ).

  • Chris Cavanagh // October 21, 2008 at 1:27 pm | Reply

    shikha – You can also use things like RegisterClientScriptInclude and RegisterClientScriptResource to serve up your script (through WebResource.axd). Take a look at these:

    http://msdn.microsoft.com/en-us/library/kx145dw2.aspx
    http://bytes.com/forum/thread606473.html

    Note you’ll probably need to uncomment some lines in Global.asax [see my sample] to prevent .axd’s being routed inappropriately.

  • ASP.NET Routing revisited (again) « Chris Cavanagh’s Blog // October 21, 2008 at 1:35 pm | Reply

    [...] 18, 2008 · 1 Comment I’ve updated my ASP.NET 3.5 + System.Web.Routing sample based on some great feedback and questions.  It’s much simpler and gives a better [...]

  • prabhjot singh // October 22, 2008 at 2:04 am | Reply

    sir,

    Thanks for the sample project.

    now the scenerio is something like this:

    1. All my pages are in the one folder.
    2. My static and dynamic routing is working.

    If i click on the page on which i haven’t implemented routing, that page is displayed, but when i again click onto the page that uses routing, the url which is shown is incorrect and the page is not getting displayed.

    eg

    my folder name is abc
    my site name is mysite

    i have done like this

    <url =”~/abc/index.aspx”

    for this the url which is displayed is
    mysite/index

    now when i click on the page working without routing eg home. It opens up

    when i again click onto index page , the url it shows is
    mysite/abc/index. it picks up folder name as well, which should not happen.

    Coding in the global.asax is just fine and according to your project.

    Please suggest something.

  • prabhjot singh // October 22, 2008 at 2:14 am | Reply

    sir,

    Thanks for the sample project.

    now the scenerio is something like this:

    1. All my pages are in the one folder.
    2. My static and dynamic routing is working.

    If i click on the page on which i haven’t implemented routing, that page is displayed, but when i again click onto the page that uses routing, the url which is shown is incorrect and the page is not getting displayed.

    eg

    my folder name is abc
    my site name is mysite

    i have done like this
    anchor tag=”index”
    <url =”~/abc/index.aspx”

    for this the url which is displayed is
    mysite/index

    now when i click on the page working without routing eg home. It opens up

    when i again click onto index page , the url it shows is
    mysite/abc/index. it picks up folder name as well, which should not happen.

    Coding in the global.asax is just fine and according to your project.

    Please suggest something.

  • Chris Cavanagh // October 22, 2008 at 5:35 am | Reply

    prabhjot – How are you generating your URLs? Are you using the GetVirtualPath helper with a named route?

    Any possibility of sending me a sample project so I can debug it?

  • prabhjot singh // October 22, 2008 at 5:48 am | Reply

    sir, I am using the GetVirtualPath helper with named route only. I am using the same concept as you did in your sample project.

    But the URL generated is not correct when i go back to the index page, and the page is not displayed. the url generated is

    mysite/abc/index rather than

    mysite/index

    please suggest a solution.
    sir you have been immensily helpful and i thank you.

  • Chris Cavanagh // October 22, 2008 at 6:54 am | Reply

    prabhjot – Could you paste some code for me to look at? I’d be interested in seeing the routes you’ve configured and the parameters you’re passing to GetVirtualPath.

    Thsnks!

  • prabhjot singh // October 22, 2008 at 7:21 am | Reply

    sir, this is the coding i’ve done in the index page.

    objStringBuilder.Append(““);

    This i have written in the global.asax file

    var searchhandler = new WebFormRouteHandler(“~/Logged/index.aspx”);
    routes.Add(new Route(“index”, searchhandler));

    This i have written in the master page coding

    Home

    sir, is it possible i take out all the .aspx pages from the folder and put them directly in the root directory. will that work fine ?

    The WebFormRootHandler is the same which you have used in your sample page.

    Thanks.

  • prabhjot singh // October 22, 2008 at 7:24 am | Reply

    sir the coding part is not getting displayed properly

    i don’t know wt to do

  • Chris Cavanagh // October 22, 2008 at 7:41 am | Reply

    prabhjot – No worries about how the code appears on this page; all comments get emailed to me and look fine…

    Could you email your project to blog@chriscavanagh.com?

    I think the problem is with the anchor tag you have in the Master Page; it looks like you’re using just “index” as the relative path. See my response to shikha above; the browser will try to create a URL based on the current request with “index” at the end (it doesn’t understand anything about server routing itself, so makes the best guess it can). Try generating your ‘home’ anchor like this:

  • Chris Cavanagh // October 22, 2008 at 7:43 am | Reply

    I hit the same comment posting problem :) Trying again…

    ActionLink( GetVirtualPath( “index”, null ), “Home” )

  • prabhjot singh // October 22, 2008 at 11:05 pm | Reply

    hello sir,

    i have defined my relative paths in the master page itself. like for index page i have written
    anchor tag= “index”

    without routing it was

    anchor tag= “index.aspx”

    in the master page i can’t call the ActionLink method. Rest of the coding i have done in the Global.asax file, same as your sample project.
    i sent you the sample code y’day.

    Is there something i can do?

  • Chris Cavanagh // October 22, 2008 at 11:25 pm | Reply

    prabhjot – Actually you *can* call page methods from the Master page. If you make the ActionLink and GetVirtualPath methods in RoutablePage public (or internal if you prefer), then add something like this to your Master Page (either server script or codebehind):

    protected new SimpleRoutingTest.RoutablePage RoutablePage
    {
    get { return Page as SimpleRoutingTest.RoutablePage; }
    }

    Then use it like this in your master page:

    = RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )

    Unfortunately I didn’t get your sample project :( (maybe my email server blocked it). Howabout uploading it to Codeplex or Google Code? :)

  • prabhjot singh // October 23, 2008 at 1:52 am | Reply

    sir, now i have written something like this

    <a href=”"”> Home

    in the master page

    protected new abc.RoutablePage RoutablePage
    {
    get { return Page as abc.RoutablePage; }
    }

    The error which it shows is in the master page is
    Object reference not set to an instance of an object.

  • prabhjot singh // October 23, 2008 at 9:49 am | Reply

    sir,

    i’ll send you my sample project

  • Leigh // October 24, 2008 at 2:28 pm | Reply

    A superb blog!

    It’s all up and running nicely for me in my current project, but I do have the following queries:

    1) How can I access the RouteData from the master page? I have a control on the master page that used to use parameters from the querystring, but now it needs to retrieve the values from RequestContext.RouteData. How can I achieve this?
    2) My sitemap driven navigation has stopped working. For example, my sitemap contains an entry for “/forumthread.aspx”. “/forumthread.aspx?fid=123&tid=456″ used to correctly highlight the associated forumthread.aspx node in the navigation tree. This url for this page is now “/forum/123/thread/456″. I have no idea how to translate this into something that can go in the sitemap, as the 123 and 456 values are determined at runtime. Any ideas?

    Thanks for such an informative post.

  • Chris Cavanagh // October 24, 2008 at 9:12 pm | Reply

    Leigh – Thanks for the feedback :)

    1) If you’re using the RoutablePage base class, it already holds a reference to the RequestContext (IRoutablePage has a ’set’ property). The simplest solution is add a public getter for RequestContext (or specifically RouteData if you prefer). In your Master Page you can then just use ( Page as RoutablePage ).RequestContext.RouteData ….
    2) The SiteMap mechanism already supports routing pretty well :) although it takes a little coaxing. Check back here in the next few days; I’ll be posting something that should help.

  • Leigh // October 27, 2008 at 5:36 am | Reply

    Thanks for the pointer Chris.

    I look forward to your next blog :)

    I’m soooo glad I found your site! It’s made my life so much easier…

  • prabhjot // November 3, 2008 at 6:45 am | Reply

    hello sir
    i m nevigating the url from master page.
    as you have given us the follwoing code to user Routerpage class
    protected new SimpleRoutingTest.RoutablePage RoutablePage
    {
    get { return Page as SimpleRoutingTest.RoutablePage; }
    }

    Then use it like this in your master page:

    = RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )

    i have used this and in global.aspx
    i have set the path like

    routes.Add( “index”, new Route( “index”, new WebFormRouteHandler( “~/Log/index.aspx” ) ) );

    But on building the solution it is giving me object refrence null.

    can u plz suggest .what the point we are missing here.
    thanks

  • Leigh // November 3, 2008 at 7:01 am | Reply

    >The SiteMap mechanism already supports routing pretty well, although it takes a little coaxing

    Are there any existing sites that detail what is required to get SiteMaps working with (for example) “/forum/123/thread/456″?

    Thanks

  • prabhjot // November 3, 2008 at 7:24 am | Reply

    respected sir,

    i have menus in my master page which get implemented with CSS files, but when i execute my project the following error is displayed, object reference not found at

    = RoutablePage.ActionLink( RoutablePage.GetVirtualPath( “index”, null ) )

    please suggest something

    regards

    prabhjot singh

  • ASP.NET Routing + just enough rope « Chris Cavanagh’s Blog // November 7, 2008 at 2:49 am | Reply

    [...] 6, 2008 · No Comments If you’ve played with the new ASP.NET routing stuff with WebForms, you probably encountered some issues with relative paths to static content (css, Javascript files [...]

  • prabhjot Singh // November 11, 2008 at 2:57 am | Reply

    Respected sir,

    I am highly grateful to you, you have been immensely helpful, as you said about the path of CSS and Js are exactly coming as you said with the funky URL we have used for routing. Can you plz be more clear about where should i put the base URL function or where i can define the exact path of CSS and Js as i am not using themes.

    Secondly, iam also facing the issue of dynamically generated path in XML e.g.
    iam generating dynamic links in XML for my pages

    Thirdly, In global.asax we have defined routable Url with given id’s, but sometimes it picks the wrong id’s , to be very precise it picks the name of my js files.

    suggest something as iam stuck here.

    regards and i obliged

    prabhjot singh

  • Pawan // November 14, 2008 at 1:04 am | Reply

    HI Chris,
    I m new to you site and i m using your contents you provided and thank you so much for providing such a great help.
    Right now i m facing an issue related to url routing.
    how do i rout the links which i dynamically created in javascript functions.is there anyway for this.please can you provide me any coding stuff for that.

    thanx
    pawan

  • Chris Cavanagh // November 14, 2008 at 8:05 am | Reply

    Pawan – Could you send me some sample code to look at? (I’d like to see how you’re currently generating the links).

    It’d be great if you could also send me an outline of your site structure (folders etc) and sample URLs you’d “like” to use…

  • Mike // November 17, 2008 at 11:46 pm | Reply

    Hi, thank you for the post.
    I am able to get routing working using a small test site and the VS 2008 webserver. However, when I setup a virtual server in IIS and change my site in VS to debug with that webserver, I am unable to get the routing to work. I can’t even hit a breakpoint in Application_Start. In my browser I get a page cannot be found error, since the URL isn’t to a real page. Do you have any suggestions? Thanks!
    Mike

  • Chris Cavanagh // November 18, 2008 at 1:10 am | Reply

    Mike – Which version of IIS are you using? This post includes some IIS7 details, but if you’re using IIS6 you’ll need to set up a “wildcard mapping”…

    Try this page and let me know if it helps:

    http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true

  • Mike // November 18, 2008 at 5:43 pm | Reply

    I am actually using IIS 5.1 in XP. I’ll need to save this project for another day I think, when I can setup a 6.0 or 7.0 server. Thanks.

  • Chris Cavanagh // November 18, 2008 at 8:50 pm | Reply

    Mike – I’ve not tried this in IIS5, but if it supports wildcard application mapping it should work fine (basically it routes EVERY request through ASP.NET; you need to uncheck “check if file exists” so that it doesn’t assume the URL relates to a physical file).

  • Leigh // November 19, 2008 at 3:36 am | Reply

    >The SiteMap mechanism already supports routing pretty well although it takes a little coaxing. Check back here in the next few days; I’ll be posting something that should help.

    Hi Chris. Are you still planning to blog on this?

  • Chris Cavanagh // November 19, 2008 at 11:10 pm | Reply

    Leigh – Thanks for the reminder! I still plan to post something :)

    As I recall, the can have your “routed” url (in its ‘url’ attribute) but I need to look again at how it handles parameters passed as path elements. The “coaxing” I mentioned might involve a custom SiteMapProvider.

  • prabhjot Singh // November 20, 2008 at 6:16 am | Reply

    respected sir,

    Thanks for helping me all through. My site is up and running with the clean URL concept and it looks really great.

    Sir , one last thing which i wanted to ask from you is that, if i am using a mehod e.g.

    abc.aspx?ID=&View=inc”)

    how will i convert this thing into routable format, i mean what i have to write? I have written this code in the client side.

    prabhjot singh

  • Chris Cavanagh // November 20, 2008 at 6:54 am | Reply

    Hi Prabhjot – One way might be to use the server-side URL helper functions to create a “base” URL and put that into the page, then create the “real” URL client-side. So something like this on the server-side (note I’ve replaced angle brackets with [ and ] so I can type them here:

    …[div]
    [script type="text/javascript"]
    var baseUrl = “[%= GetVirtualPath( null ) %]“;
    var realUrl = baseUrl + “/inc”;
    [/script]
    [/div]

    (Hope this is readable! I might need to code up a sample of this too :) )

  • Jim // November 21, 2008 at 12:18 pm | Reply

    Chris,

    Similar to Mike’s issue, I am trying to get routing to work on IIS 6 after having it work on my box with IIS 7. I looked at the Microsoft page you referred Mike to, but I am unsure *which* DLL I am suppose to specify when adding the wildcard mapping. Is it a system one? One of my own?

    Thanks,
    Jim

  • Chris Cavanagh // November 21, 2008 at 3:00 pm | Reply

    Jim – You need to point it to the ASP.NET ISAPI extension, typically located here:

    c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll

    Hoep this helps!

  • Jim // November 21, 2008 at 5:19 pm | Reply

    Chris,

    Thanks for the response. One last question.

    One additional thing I wanted to do was to have the served file (a PDF in this case) to appear to come from a sub folder in the web site. Now, if I add the filter to the top level of my site (I specifically tried an application extension and not the wild card), it works, but I can’t then serve up any real unsecured PDF. So, I created a folder with the same name as where the route SAYS it is coming from and put the filter there. Now when I try and access the special PDF, I get a connection error in IE and Firefox does nothing.

    If you have any clues, I would appreciate a push in the correct direction.

    Thanks,
    Jim

  • prabhjot // November 23, 2008 at 11:12 am | Reply

    hi chris,
    Thanks for your response,

    Iam still stuck with the databinder issue.
    the code i have written is something like this
    ‘[%#DataBinder.Eval(Container.DataItem,"id")%].

    Secondly, if iam using handlers in my project, how can i convert them into routable format, it will be good if you post a sample project.

    prabhjot singh

  • Jim // November 24, 2008 at 11:28 am | Reply

    Chris,

    OK, I figured it out/made a work around. Since my secured pdf will always be routed with one static name, I simply added a new route to handle generic PDF files and have it serve them up.

    Thanks for a great article.
    Jim

  • Leigh // November 26, 2008 at 5:36 am | Reply

    >Leigh – Thanks for the reminder! I still plan to post something

    Glad to hear that. The SiteMap aspect of routing is causing me some problems…

  • prabhjot // December 2, 2008 at 6:53 am | Reply

    hi chris,
    i am back again, thanks for your help.
    sir, i am using IIS6, i am using wild card mapping concept, but it has scalability problem, i want to shift to 404 approach(extension less routing)

    I have implemented everything , i have changed the custom errors. i have written the required code in the global file. but when i run it on the server it shows “The resource cannot be found.”. what more should i do?

    Regards
    Prabhjot

  • Chris Cavanagh // December 2, 2008 at 7:08 am | Reply

    Prabhjot – Phil Haack recently blogged about this (relative to MVC, but same basic issues). Let me know if it helps: http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx.

  • prabhjot // December 2, 2008 at 8:29 am | Reply

    But i have made my project without using the MVC approach.

    Thanks

    prabhjot

  • Mike // December 7, 2008 at 10:54 am | Reply

    What about Session state? Any page I access via a route looses it’s Session. I’ve tried both your and Phil’s version but Session is always null. All pages accessed directly without a route have Session fine. Any thoughts?

    Thanks-

  • Chris Cavanagh // December 7, 2008 at 9:59 pm | Reply

    Prabhjot – Phil’s post was about getting IIS6 working with ASP.NET’s routing (regardless of whether using MVC or not). Any progress getting it working?

  • Zakhar // December 15, 2008 at 8:21 am | Reply

    hi chris. Could you please tell me, how can i do next: i need to change navigate url depends on route data. For expample:

    Route rt3 = new Route(“Treeview/{advert}/{variant}/FunctionTree”, new WebFormRouteHandler(“~/WebForm2.aspx”));
    rt3.Defaults = new RouteValueDictionary(new { stage= “1″, variant = “1″ });
    rt3.Constraints = new RouteValueDictionary(new { stage= @”\d{1,2}”, variant = @”\d{1,2}” });
    //rt3.GetRouteData(HttpContext.Current);
    routes.Add(rt3);

    I need to change url if the parameter “stage” is equal to “12″ for example. “~/webform3.aspx”. How can i do this? Thanks in advance.

  • Chris Cavanagh // December 15, 2008 at 10:28 am | Reply

    Zakhar – Could you confirm what you mean by “change url”? If you’d just like “stage=12″ to be handled by another RouteHandler, then you could just add another route, something like this (I’m guessing “advert” should be “stage” in your example?):

    var rt4 = new Route( “TreeView/12/{variant}/FunctionTree”, new WebFormRouteHandler( …..

    I haven’t tested this though. Let me know if I’m barking up the right/wrong tree :)

  • Leigh // December 19, 2008 at 5:28 am | Reply

    Possibly a stupid question, but how/where do I catch the SecurityException that is thrown in GetHttpHandler? I want to simply display a message informing the user that they do not have permission to view the page. Ideally, I’d like to catch it one, in my MasterPage (rather than in each individual page).

  • Samuli Lintunen // December 23, 2008 at 11:18 am | Reply

    Leigh,

    I replaced the tad ambiguous SecurityException with a HttpException and
    gave it the http response status code of 401 “Unauthorized” (http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error). The reasoning being that since routing belongs to the System.Web namespace (System.Web.Routing) and System.Web (http://msdn.microsoft.com/en-us/library/system.web.aspx) deals with http-related things as does the GetHttpHandler; throwing a (401) HttpException is acceptable, perhaps more desirable than a generic SecurityException in the context of
    checking user permissions on the web. The HttpException is then handled at the application level in global.asax.cs in the Application_Error section according to its status code.

    You might want to check out the following link:
    http://stackoverflow.com/questions/55961/exception-handling-in-net-web-apps

  • pankaj // January 12, 2009 at 8:51 pm | Reply

    Hi Chris, I am using the .net 3.5 SP1’s url re-routing and having some issues with virtual path of the web application.
    If the virtual path in the web project’s property (in VS ‘08) is set to ‘/’, then things work just fine, but when I changed the value to ‘/My.WebApp’, the url re-routing fails and I get a 404 – The resource cannot be found.

    Here is the route that I am registering:
    RouteTable.Routes.Add(new Route(“{PartnerName}/RegisterUser”, new MyRouteHandler(“~/RegisterUser.aspx”)));

    This is the url on the browser with virtual path = ‘/’
    http://localhost:1622/panasonic/registeruser.aspx

    and this is the one with virtual path = ‘/My.WebApp’
    http://localhost:1622/My.WebApp/panasonic/registeruser.aspx

    Any help is greatly appreciated.

    • Chris Cavanagh // January 12, 2009 at 9:50 pm | Reply

      pankaj – Have you tried running the site under IIS? I haven’t [yet] tried routing with Visual Studio’s webserver using a different (not “/”) virtual path. It doesn’t completely surprise me there are a couple issues though. It’ll probably need some more experimentation to get right (I’ll look into it as soon as I can).

      What’s the reason you’re needing a different path in Visual Studio? You should find the site works great running directly in IIS, but let me know if you’ve found otherwise…

      Hope this helps! :)

  • pankaj // January 13, 2009 at 11:52 am | Reply

    Chris, the site does not work even in IIS when deployed under a virtual directory.

    Although, my lucky stars, we found the solution. If I register the routes as (notice the .aspx in the first param of Route’s ctor)

    RouteTable.Routes.Add(new Route(”{PartnerName}/RegisterUser.aspx”, new MyRouteHandler(”~/RegisterUser.aspx”)));

    things work great, except now I also have to type in the file extension in the url…but I am not complaining.

    :)

  • Paolo // January 14, 2009 at 3:11 pm | Reply

    Thanks Chris, the version in VB.net?

  • Chris Cavanagh // January 14, 2009 at 4:06 pm | Reply

    Hi Paolo – Yes I’d love a VB.Net version! You wanna write it for me? ;)

    But obviously, a very good point. It’s now on my todo list :)

  • Paolo // January 15, 2009 at 8:54 am | Reply

    Hello Chris, I tried to convert it to VB but I have an error in the classroom.
    the error is here: Implements IRouteHandler.
    Sorry for English, but I am an Italian. Hello

  • What is the version of the Integrated Server (VS Studio 2008 SP1) | keyongtech // January 18, 2009 at 10:40 am | Reply

    [...] having to create tons of routing rules. > Yes I followed a tutorial on Chris Cavanagh’s blog (http://chriscavanagh.wordpress.com/2…url-rewriting/) and I can’t get it to work on VS Studio 2K8 (both Express and Pro). The Routing handler never [...]

  • Paolo // January 19, 2009 at 5:44 pm | Reply

    Hello Chris, thanks for the help.
    I used the tool to convert developerfusion.com in vb.net: http://www.developerfusion.com/tools/convert/csharp-to-vb/

    but the example does not work. The class is not used in the code region

  • Chris Cavanagh // January 20, 2009 at 12:38 am | Reply

    Paolo – No worries; I’ve created a VB.NET sample project for you :) Check out my post here:

    http://chriscavanagh.wordpress.com/2009/01/20/aspnet-routing-in-vbnet/

    Let me know if any problems!

  • Leigh // February 17, 2009 at 8:32 am | Reply

    Thanks Samuli

    I took your advice and switched to throwing an HttpException. It’s all working perfectly and cleanly. I appreciate your help, as this was something I didn’t know how best to handle.

  • Leigh // February 24, 2009 at 4:29 am | Reply

    Has anyone managed crafted a routing aware sitemap for this stuff? My next project needs to be sitemap based, so I might have to drop routing :(

  • Chris Cavanagh // February 25, 2009 at 4:29 pm | Reply

    Leigh – I’ve successfully used sitemaps with routing (through a custom SiteMapProvider). However my use cases were unusual / weird :) This may be a better example…:

    http://blog.maartenballiauw.be/post/2008/08/29/Building-an-ASPNET-MVC-sitemap-provider-with-security-trimming.aspx

  • Leigh // February 26, 2009 at 5:12 am | Reply

    Thanks for the link Chris. I’ll take a look now…

  • Prk // February 27, 2009 at 8:01 am | Reply

    Hi.

    I just installed VWD with .net framework 3.5 and it seems that the System.Web.Routing is not included as c# tells me.. what should i do?

  • Chris Cavanagh // February 27, 2009 at 9:27 am | Reply

    Prk – Make sure you install .NET 3.5 Service Pack 1. That should include the routing assemblies :)

  • GK // March 4, 2009 at 12:51 am | Reply

    Hi,

    I have created project which implemented URL routing using System.Web.Routing.

    Everything is working fine. Now i got problem is,
    i created a page with server side button. On button click, i am doing something. Initially URL is fine like http://localhost:2263/TestRouting/show/markets/1 but when button is clicked, the address bar shows the actual aspx like http://BaseURL/markets/test.aspx?section=markets&pageno=1

    How to retain the same URL in address bar like http://localhost:2263/TestRouting/show/markets/1 instead of showing actual .aspx.

    Please help, looking for your suggestion….

  • Chris Cavanagh // March 4, 2009 at 1:10 am | Reply

    GK – If you put a breakpoint in your WebFormRouteHandler, does it get hit? Sounds like there’s a Response.Redirect happening somewhere (or some old rewriting code) rather than using routing…

  • Samuli Lintunen // March 8, 2009 at 9:25 am | Reply

    Leigh, I’m glad I could be of some help to you. :)

    Big Thanks to Chris (and Phil) for providing the original work.

  • ASP.NET Hosting : Using ASP.NET MVC Routing to route the 404 Error Pages // March 20, 2009 at 1:41 am | Reply

    [...] implementation (example created by Chris Cavanagh)        // see http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/      &nbsp; var startPageRouteHandler = new [...]

  • Using ASP.NET MVC Routing to route the 404 Error Pages « ASPHostCentral - .NET3.5 Hosting & SQL Express Hosting // March 23, 2009 at 8:51 pm | Reply

    [...] // reference IRouteHandler implementation (example created by Chris Cavanagh)         // see http://chriscavanagh.wordpress.com/2008/03/11/aspnet-routing-goodbye-url-rewriting/         var startPageRouteHandler = new [...]

  • Andy // March 30, 2009 at 2:49 am | Reply

    I’m new to ASP.Net routing – is this technology reliant on IIS7? Having read different blogs and articles I’m getting conflicting information. I want something that will work on IIS 6.0 without having to install/configure anything within IIS.

    Thanks in advance
    Andy

  • Chris Cavanagh // March 30, 2009 at 8:24 am | Reply

    Hi Andy – It’ll work in IIS6 but you do need to change a setting on your app in IIS that essentially sends *every* request to ASP.NET (even static content files). It’s called Wildcard Application Mapping and it’s mentioned a bit in this post:

    http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/

    Hope this helps!

  • Leigh // April 10, 2009 at 10:42 am | Reply

    I’m finding that, when initially logging into the site, the CSS appears to be missing – The log in page has no style! After successfully logging in, everything is fine on subsequent log ins. Can anyone explain this, and how can I fix it?

    Thanks

  • Chris Cavanagh // April 10, 2009 at 10:45 am | Reply

    Leigh – I’ve seen this a few times with regular ASP.NET apps. Try adding some ‘location’ elements in your web.config to exclude your .css files from forms authentication. Do you get the same issue running under IIS, or just under VS/Cassini?

  • Leigh // April 10, 2009 at 7:10 pm | Reply

    Thanks Chris. I think you might have hit the nail on the head there. I bet access to the CSS is being denied, due to my default settings. Thanks for the heads up! I’ll take a look…

  • Evol // April 15, 2009 at 5:34 pm | Reply

    Has anyone experienced the following issue:

    Could not load file or assembly ‘NameSpace’ or one of its dependencies. The system cannot find the file specified.

    namespace NameSpace
    {
    ///
    /// Simple UrlRoutingHandler implementation
    ///
    public class RoutingHandler : UrlRoutingHandler
    {
    protected override void VerifyAndProcessRequest( IHttpHandler httpHandler, HttpContextBase httpContext )
    {
    }
    }
    }
    The class “UrlRoutingHandler” is as above and I have no problems running the site under VS08 or in IIS6.

  • Chris Cavanagh // April 16, 2009 at 11:51 am | Reply

    Evol – Interesting error. Could you send me a sample project?

  • localman // April 22, 2009 at 11:17 pm | Reply

    If anyone reads this post for prabhjot’s “The resource cannot be found.” error, make sure you double check your web.config matches the one in the example. Had the example running fine, but my app not. knew it had to be in there somewhere.

  • Leigh // April 28, 2009 at 7:21 am | Reply

    Aargh! I’m unable to use cross page posting with routing. Attempting to use the PreviousPage property results in an HttpException, because the routed page doesn’t physically exist. Does anyone know of a way around this?

  • Leigh // April 28, 2009 at 4:21 pm | Reply

    Ignore that – I worked around it.

    I never did get a sitemap working with this stuff though. The MVC sitemap is simply too rigid for general routing (i.e. not using controllers and actions etc).

  • Rod // May 4, 2009 at 9:54 pm | Reply

    Hi -

    I am getting the same error as Evol (above): “Could not load file or assembly ‘SimpleRoutingTest’ or one of its dependencies.”

    I used your VB sample with no alterations. It runs fine on my local machine, but not on my web server. The server is running IIS 7, .NET 3.5, but I obviously am overlooking a setting. Do you have any ideas?

  • priyanka // May 10, 2009 at 10:03 am | Reply

    Hi Sir,
    I need your help implementing breadcrumb or sitemap in asp.net routing website. Plz help me…….. as soon as possible……….

  • tso // May 12, 2009 at 4:27 am | Reply

    how do I retrive parameter values from querystring when I use Routing

  • Sandeep Aparajit // May 15, 2009 at 4:49 am | Reply

    Hi Chris,

    I had a query related to ASP.NET URL Routing functionality. At present even if the sitemap is not provided, the search engine crawlers crawl the website to find indexable pages. But with ASP.NET MVC patterns, we would have one single (controller) class serving multiple URL’s. Then is it made mandatory to provide an xml sitemap with the website? If not, then how will the search engine crawler be able to crawl our URL’s?

  • Chris Cavanagh // May 15, 2009 at 7:53 am | Reply

    Sandeep – I’m not sure it would matter… I don’t know the rules the crawlers use, but I’d guess that as long as every possible page was linked from somewhere in your site you’d be ok (I’d also guess Googlebot etc allow you to identify your own search pages it can delegate requests to, or maybe not… need to ask an SEO expert :) ). As for the single controller serving multiple URLs, clients/spiders would never be aware of that (they’d only see public URLs we expose)… Lat me know if I misunderstood your question though and I’ll have a closer look!

  • Sandeep Aparajit // May 18, 2009 at 9:31 pm | Reply

    Ya Chris, I agree to the fact that the spiders would never be aware of a single controller serving multiple URLs. I think the search engine spiders would be intelligent enough to search for public (exposed) URLs.

    Thx!

  • ASP.NET WebForm Routing with SiteMaps « Chris Cavanagh’s Blog // May 19, 2009 at 10:36 pm | Reply

    [...] 19, 2009 · No Comments I’ve updated my ASP.NET WebForm Routing demo with basic SiteMap support.  It’s targeting ASP.NET 3.5 SP1 and expects your WebForm [...]

  • Chris Cavanagh // May 20, 2009 at 9:34 am | Reply

    Leigh – If you still need some help with routing + SiteMaps, I’ve posted something that might help:

    http://chriscavanagh.wordpress.com/2009/05/19/asp-net-webform-routing-with-sitemaps/

  • Issa Qandil // May 20, 2009 at 12:51 pm | Reply

    Hello Chris,

    I was wondering if you had any problem regarding postback with urls like this one :

    [http]://[SomeDomain]/Cat/Product/ID/

    If you looking into the generated page source you will notice that the form do a post with only the last action … i mean something will look like this:

    Which will cause a server error due to the validation of the posted page … any ideas solving this.

    Thanks,
    I. Qandil

  • Chris Cavanagh // May 20, 2009 at 1:33 pm | Reply

    Issa – I’d not seen this before (but have now, thanks! :) ). This seems to be the same issue:

    http://stackoverflow.com/questions/230014/postback-not-working-with-asp-net-routing-validation-of-viewstate-mac-failed

    I’ll dig into this some more and post an update…

  • Chris Cavanagh // May 20, 2009 at 1:55 pm | Reply

    Issa – This looks like the same problem:

    http://stackoverflow.com/questions/230014/postback-not-working-with-asp-net-routing-validation-of-viewstate-mac-failed

    Unfortunately we need a hack to fix it :( The main problem appears to be the s ‘action’ value is incorrect. A workaround is suggested here:

    http://www.andreas-kraus.net/blog/404-error-while-using-aspnet-url-routing/

    Until I find / figure out a better solution, I’ve added this to an OnLoad override in RoutablePage.cs:

    Form.Action = HttpContext.Current.Request.RawUrl;

    Hope this helps!

  • Issa Qandil // May 20, 2009 at 2:17 pm | Reply

    Yep it is the same problem as in SO.

    Your suggestion is great but shouldn’t that be placed in the page itself encase you need to do other things in OnLoad ?

    Maybe putting it in another step in the PageLife Cycle

    What do u think ?

  • Chris Cavanagh // May 20, 2009 at 2:28 pm | Reply

    Issa – Here’s a better idea… Add some code into WebFormRouteHandler like this:

    var webForm = page as Page;
    if ( webForm != null ) webForm.Load += delegate { webForm.Form.Action = requestContext.HttpContext.Request.RawUrl; };

    Same end result, but avoids polluting the page with an obvious hack :)

  • Issa Qandil // May 20, 2009 at 2:34 pm | Reply

    And that’s what i call magic,

    I was thinking of doing it from that place just before returning the page but i guess i was stuck

    Thanks for you help i guess i will try it.

  • Issa Qandil // May 20, 2009 at 2:40 pm | Reply

    And it did work perfectly … thanks

  • James Talbot // May 21, 2009 at 5:10 am | Reply

    Hi, I’ve used routing for a bit now and have got it to work in a number of scenarios.

    I’m now trying to see if I can get it to dissect the queryvalues of an originating url. i.e. if someone types http://www.mydomain.com/page.aspx?id=x then I want to reroute to a different page based on x.

    I have the following line in global.asax.

    Routes.Add(New Route(“page.aspx/{*pathInfo}”, New RouteHandler()))

    However I can’t seem to get a value out for x in the RouteHandler.

    I’ve tried accessing requestContext.RouteData.GetRequiredString(“pathInfo”) which is nothing.

    and also tried going through the routedata.

    Dim qs = New StringBuilder(“?”)
    For Each aux In requestContext.RouteData.Values
    qs.Append(HttpUtility.UrlEncode(aux.Key))
    qs.Append(“=”)
    If Not aux.Value Is Nothing Then qs.Append(HttpUtility.UrlEncode(aux.Value.ToString()))
    qs.Append(“&”)
    Next
    qs.Remove(qs.Length – 1, 1)

    Using this the key for pathInfo exists but the value is nothing…

    Any ideas where I might be going wrong.

    Thanks in advance.

  • James Talbot // May 21, 2009 at 5:31 am | Reply

    Following on from my last post I decided to work with requestContext.HttpContext.Request.RawUrl which exposes the querystring values. Although this has solved my problem for the time being it would be good to know if I can go about it the other way.

  • Chris Cavanagh // May 21, 2009 at 12:50 pm | Reply

    James – Since you’re just after the querystring parameters, could you just set your route as:

    Routes.Add( New Route( “page.aspx”, new CustomRouteHandler(…) ) )

    …then in your CustomRouteHandler implementation just grab requestContext.Request.QueryString( “x” ) and create the appropriate page …. ?

    Your previous route with {*pathInfo} should do great capturing things like http://www.mydomain.com/page.aspx/my/sub/path (and will probably ignore querystring params).

    Let me know if this helps (or if I misunderstood! :) )

  • James Talbot // May 22, 2009 at 6:12 am | Reply

    I’m sure that would do it yes. Thanks for the advice. I was too busy trying to break the routing module than consider using much simpler methods!

  • Sathish // June 29, 2009 at 12:52 am | Reply

    Hi Chris,

    I have implemented URL Routing in one of my project and it works fine. But i am not able to set the default page in my site. Suppose i enter “http://localhost/sitename/” it dosent take me to default.aspx page. Instead it gives me 404 error. Kindly help me out.

    Thanks in advance

  • Windows Web Hosting // July 6, 2009 at 6:17 pm | Reply

    This sounds really great. Routing removes the need of rewriting the URL. Thanks, will switch to this soon.

    We are currently using Intelligencia.UrlRewriter component for rewriting, does this component need full trust asp.net level?

    Thanks in advance.

  • Chris Cavanagh // July 6, 2009 at 9:28 pm | Reply

    Marvin – The routing assemblies don’t need full trust. However, if you’re using IIS6 you’ll need to enable Wildcard Application Mapping (http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true) to send all requests through ASP.NET.

    Hope this helps!

  • Chris Cavanagh // July 6, 2009 at 9:39 pm | Reply

    Sathish – Are you using IIS 6, 7 or VS’s web server? You might need to define an additional fallback route to catch requests like that, or maybe tweak some IIS settings. See if this helps (can skim over dynamic data stuff): http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx

  • Kandaiya // July 21, 2009 at 4:15 am | Reply

    Hi,

    Is it possible to do URL routing to handlers like .ashx.

    I got situation to redirect my requests to .ashx handler.

    In simple, like Routes.Add(“/departments/accounts”,”depart.ashx”);

    Thanks

  • Chris Cavanagh // July 21, 2009 at 4:44 am | Reply

    Kandaiya – I’ve not tried it with handlers; I guess it just comes down to whether BuildManager.CreateInstanceFromVirtualPath can handle .ashx’s or not. I’ll try it out :) (but let me know if you figure it out sooner!).

  • How to build huge dynamic cross platform Silverlight Business Applications « An Original Idea // July 21, 2009 at 6:52 pm | Reply

    [...] Goodbye to Url Rewriting [...]

  • Leigh // August 3, 2009 at 6:31 am | Reply

    Should output caching work with routing? I’m currently writing a web site that would benefit from caching, but it simply doesn’t seem to be working. I’m wondering if there are any known issues with routing and output/partial caching?

  • Chris Cavanagh // August 3, 2009 at 8:49 am | Reply

    Hi Leigh – Good question; I don’t have a clue! If it’s not behaving as expected, it might be worth looking at what’s coming in ASP.NET 4 (or the latest futures stuff); might be something they’re addressing with the improved WebForms / routing support…

    All I can suggest is get as many breakpoints in as you can; if all the requests are coming in as expected, I’d hope/expect it’d be relatively easy to diagnose. Let me know what you find (meanwhile I might kick it around in a test project).

  • Leigh // August 4, 2009 at 3:41 am | Reply

    False alarm Chris. It does appear to be working as expected now.

    Thanks again for this stuff – I use it in every one of my sites now.

  • Abhinav Agrawal // August 26, 2009 at 3:15 am | Reply

    Hi chris
    I am using free text box control on a .ascx file ie on a control file, on this there is a browse image option. On the page where routing is implemented and a control is used and in that control this free text control is used, because of why when we click browse image, wrong page gets open. This can not be changed as it is coming from a DLL

  • Chris Cavanagh // August 26, 2009 at 6:29 am | Reply

    Abhinav – Have you contacted the textbox control authors? If it’s a bug in their control (likely if all your other content is working with routing) they could probably fix it pretty easily. Alternatively you could try opening the DLL in Reflector and use the FileDisassembler add-in (http://www.denisbauer.com/NETTools/FileDisassembler.aspx) to create a new source project, fix the bug yourself and rebuild the DLL :) (relatively easy if it’s not been obfuscated). Hope this helps!

  • ..:: Mãstän ::.. // October 21, 2009 at 10:50 am | Reply

    @Chris Cavanagh,

    Nice article, Thanks for it.

    I have small doubt, I tried lot find a solution, unable to get it. Its related to URL rewrite or URL mapping.
    For example I have 2 folders in my asp.net project
    1. good
    2. bad
    under this folder few aspx pages are there, whenever I access pages from this folder, in browser url it should shows that folder name only like calling http://localhost/good/page1.aspx” -> it need to show http://localhost/good, if I call page2.aspx or pageN.aspx in url it must show http://localhost/good, also same way in bad folder too.
    For example, from good folder I’m calling page2.aspx normally its shows like /good/page2.aspx in address bar, if I call page1.aspx from good folder it also shows like /good/page1.aspx, other files also shows in that way. I want to hide page name, just want to show folder name like /good or /bad. If I follow url mapping or rewrite whichever you mention here … I cant fulfill my requirements.
    how can I do this? could you help me pleaseeeeeeeeee??
    I’m using ASP.NET 3.5
    Thanks in advance.
    Please help me this poor guy
    –Mastan

  • Chris Cavanagh // October 21, 2009 at 11:35 am | Reply

    Mastan – The Routing functionality should give you exactly what you want, but you’ll need to configure it appropriately. All it does is map a url pattern to a real WebForm (aspx). In this case you’d want to create a custom RouteHandler to determine which physical .aspx should handle the request.

    Given that your required url includes the folder name, how do you intend to determine which .aspx to use? (ie, for http://localhost/good, should it hit ~/good/page1.aspx, ~/good/page2.aspx… etc).

Leave a Comment