ASP.NET Routing… Goodbye URL rewriting?

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

200 Comments

  1. 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.

    Reply

  2. […] 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: […]

    Reply

  3. 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

    Reply

  4. 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

    Reply

  5. 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 🙂 )

    Reply

  6. 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.

    Reply

  7. 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… 🙂

    Reply

  8. 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?

    Reply

  9. 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!

    Reply

  10. 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

    Reply

  11. 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

    Reply

  12. 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).

    Reply

  13. 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

    Reply

  14. 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! 🙂 ).

    Reply

  15. 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.

    Reply

  16. 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.

    Reply

  17. 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.

    Reply

  18. 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!

    Reply

  19. 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.

    Reply

  20. 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:

    Reply

  21. 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?

    Reply

  22. 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? 🙂

    Reply

  23. 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.

    Reply

  24. 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.

    Reply

  25. 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.

    Reply

  26. 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…

    Reply

  27. 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

    Reply

  28. >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

    Reply

  29. 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

    Reply

  30. 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

    Reply

  31. 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

    Reply

  32. 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…

    Reply

  33. 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

    Reply

  34. 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.

    Reply

  35. 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).

    Reply

  36. >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?

    Reply

  37. 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.

    Reply

  38. 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

    Reply

  39. 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 🙂 )

    Reply

  40. 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

    Reply

  41. 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

    Reply

  42. 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

    Reply

  43. 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

    Reply

  44. >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…

    Reply

  45. 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

    Reply

  46. 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-

    Reply

    1. I’m having the same problem Mike. Did you manage to solve it? It may be IIS 7.0 related as Session is available when run on our IIS 6.0 development machine. Other developers who also use IIS 6.0 also have no problems.

      Reply

  47. 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.

    Reply

  48. 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 🙂

    Reply

  49. 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).

    Reply

  50. 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

    Reply

  51. 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.

    Reply

    1. 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! 🙂

      Reply

  52. 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.

    🙂

    Reply

  53. 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

    Reply

  54. 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.

    Reply

  55. 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 😦

    Reply

  56. 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?

    Reply

  57. 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….

    Reply

  58. 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…

    Reply

  59. 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

    Reply

  60. 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

    Reply

  61. 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?

    Reply

  62. 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…

    Reply

  63. 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.

    Reply

  64. 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.

    Reply

  65. 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?

    Reply

  66. 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).

    Reply

  67. 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?

    Reply

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

    Reply

  69. 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?

    Reply

  70. 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!

    Reply

  71. 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!

    Reply

  72. 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

    Reply

  73. 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!

    Reply

  74. 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 ?

    Reply

  75. 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 🙂

    Reply

  76. 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.

    Reply

  77. 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.

    Reply

  78. 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.

    Reply

  79. 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! 🙂 )

    Reply

  80. 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!

    Reply

  81. 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

    Reply

  82. 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.

    Reply

  83. 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

    Reply

  84. 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!).

    Reply

  85. 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?

    Reply

  86. 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).

    Reply

  87. 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.

    Reply

  88. 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

    Reply

  89. 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!

    Reply

  90. @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

    Reply

  91. 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).

    Reply

  92. Hi Chris,
    can you please suggest me any way of routing in .net 2.0.I am rewriting URL for .html to .aspx pages.Since i don’t have access to IIS 6.0 to configure it to transfer .html request to aspnet_isapi.dll ISAPI extension, i can’t perform url rewriting for html pages.Is there any change i can do in web.config file or any other place to perform this.

    Thanks

    Reply

  93. Hi Chris, great blog!

    When I use your code in a WAP i get the same error as Evol and Rod:

    “Could not load file or assembly ‘NameSpace’ or one of its dependencies”

    Solution:

    ….

    ….

    Netboss

    Reply

  94. Amit – Without having access to the server, and being restricted to ASP.NET 2.0, your options are limited 😦 Could you send me some examples of the kind of URL’s you’re wanting to use?

    Reply

  95. oppssss! sorry I didnt see ur response here… :(( sorry sorry… again I’m facing problem in subdomain url rewrite :(, seems I’m always stucking in URL rewritting :((… can u help me again pls?

    Reply

  96. Hi,
    I implemented URL rounting partially, some of the page has routing and some dont. Now the problem i face is my forms authendication doesnt seems to work in URL routed pages but other pages it works.. When i see into my RouteHandler i can see that my context.user.identity is null. Where as in other page it has values. Basically i redirect to the routed page after authendication. Can you please let me know what could be the possible problem.. I use II7..

    Reply

  97. Hi,

    I have a requirement related to subdomains. Here are the details.

    I am using .NET 4.0, IIS7, ASP.NET 4.0. I have an web application hosted as “mycompany.com”. I have some clients, say client1, register at my site. I want to give him a

    URL like http://client1.mycompany.com. Similarly for client2 URL will be http://client2.mycompany.com

    http://mycompay.com has provision to allow new clients to register at my site. Any new client should able to view his area by using URL http://clientN.mycompany.com.

    This is very similar to Microsoft’s spaces.live.com; Each individual having hotmail/live ID can access his spaces. Ex: http://ypradeep23.spaces.live.com

    Can you please guide me in design this solution.

    Regards,
    Pradeep.

    Reply

  98. Crhis Hello, thanks for the article. I need to be replaced in VirtualPath me a parameter of the routing in WebFormRouteHandler. Example:

    var mypage = new WebFormRouteHandler(“~/{page}.aspx”);
    routes.Add(new System.Web.Routing.Route(“{language}/{page}.aspx”, mypage));

    Thank you very much 🙂

    Reply

  99. Hello,
    I have a problem when I use Routing Method in my project.
    I use .Netframework 4 and asp.net 2010.
    I generated my project by Codesmith and .NetTiers template if you want i can send my sample project for your emai?
    I read any topic about Url Routing but in my project it does not work,
    I think IRouteHandler Dose not fire what should I do Please help me.
    thanks vida .

    Reply

  100. Site Map Issue if URL contain “-m” automatically link will break

    this my Sitemap node c

    there -ma character is including.if -ma to chage any other charter than “m” link will work fine.

    i have check this with working link and if i put -m for the working url link is breaking automaticaly.

    Reply

  101. Site Map Issue if URL contain “-m” automatically link will break

    there -ma character is including.if -m to change any other charter than “m” link will work fine.

    i have check this with working link and if i put -m for the working url link is breaking automatically.

    Reply

  102. i have custom http modules which is firing twice one for original request and the other for the router, Is any one know how to prevent this?

    Reply

  103. Hi. I have used in asp.net 4 with this method :

    routes.MapPageRoute(
    “product”,
    “Product/{ProductName}.mk”,
    “~/product.aspx”
    );

    – but I have a problem
    I have links like that : http://localhost:5327/Product/car-2.mk

    when I click link , it becomes : http://localhost:5327/Product/Product/car-2.mk

    — it repeats Product/

    in product.aspx.cs I have only :
    protected void Page_Load(object sender, EventArgs e)
    {
    string category = Page.RouteData.Values[“ProductName”].ToString();

    Label1.Text = “product – ” + category;
    }
    Can you help me , thanks …

    Reply

  104. HI Chris,

    I have implement url routing on my website project in vs 2010 and IIS 7.

    But after impelemented I have facing issue where images and css some times load and some not.

    please suggest ?

    Reply

    1. khan – Is there a pattern to when the images aren’t loaded? For example, do they only load after successful authentication, but fail before that? (you may need to hit CTRL+F5 to make sure the browser is requesting them each time, and not just caching). If you can tie it down to authentication, you might just need a element in your web.config, to exclude image (and probably css) files from forms authentication: http://msdn.microsoft.com/en-us/library/b6x6shw7(v=vs.71).aspx

      Reply

  105. HI Chris,

    Thanks for your quick response.

    I don’t know about any pattern but have facing this type of issue after placed url routing.

    Some times Images are displayed and some times not.

    I really stuck last 3 days and haven’t found any solution.

    Reply

    1. khan – Try using the debugger in your browser… Most current browsers can show a “resources” list that includes all images, css files etc… If there’s an error retrieving one of them, it’ll usually tell you about it.

      How large are the images?

      Reply

  106. Hi Chris,

    It’s happen for whole the website not matter image is 2 kb or larger.

    Some time website are totally distorted because it’s not loading any css or js.

    when I refresh or browse site page by page, It’s displayed fine but again after few minutes images are not displayed.

    Reply

    1. khan – Something pretty weird going on there… Is it using IIS and running on your local machine, or deployed on a public server / host? If this is using the Visual Studio dev host (Cassine, IIS Express etc), does the same thing happen if you run in IIS and / or publish live?

      Reply

      1. Hi Chris,

        I have attached two screen shot.

        First one image is not displayed on the page and second when I have used direct url for that image it’s showing fine.

        Regards,

        Khan

        On Thu, Jan 24, 2013 at 11:45 AM, Chris Cavanagh’s Blog wrote:

        > ** > Chris Cavanagh commented: “khan – Something pretty weird going on > there… Is it using IIS and running on your local machine, or deployed on > a public server / host? If this is using the Visual Studio dev host > (Cassine, IIS Express etc), does the same thing happen if you run in II” >

    1. khan – Best guess is the routing is picking up the image requests and trying to map them to an action… Doesn’t explain the randomness, unless the browser is choosing to pull previously cached versions on the occasions it “works” (and with direct url). You might find some hints here:

      http://www.phpvs.net/2009/08/06/aspnet-mvc-how-to-route-to-images-or-other-file-types/

      Alternatively, you could create an action specifically to serve your images and resources. It’s a bit heavier than just letting IIS handle it, but could give you more control (for instance serving smaller versions of existing images):

      http://dotnetslackers.com/articles/aspnet/ASP-NET-MVC-3-Controller-for-Serving-Images.aspx

      Reply

  107. Chris,

    I have checked above url but it all about in MVC.

    I have created simple CMS and place dynamic url routing using global.asax file and all images with content comes from database.

    I have checked images are not very large in size.

    Could you please check the below link for me –

    http://www.indexksa.com

    Reply

  108. Hi Chris,

    Images is in the html content.

    It’s simply through sql query I am not using any handler. The saved content in database like below –

    As Media Partners, every one of the below publications has committed to supporting INDEX KSA in full. They dedicate sections of their news pages, schedule special features around the exhibition and can provide exhibitors with valuable additional support helping make the most of their participation.


    ITP

    Commercial Interior Design is an invaluable source
    of ideas, inspiration and product information for industry professionals across the Middle East. Commercial Interior Design has a BPA audited circulation of 6034 and has quickly become the must-read publication for industry professionals in the Middle East.
    Commercial Interior Design covers all aspects of commercial interiors, from residential to industrial, offices to warehouses, hotels to health spas and everything in between.
    Commercial Interior Design is part of the construction and design stable of titles published by ITP Business – Publisher of more trade titles than any company in the Middle East.
    For your free one year subscription to Commercial Interior Design please log on to http://www.itp.com/subscriptions

    Reply

      1. Hi Chris,

        I have attached some page and global.asax file.

        I have saved route for all page in database and fetch route from database through global.asax (application beginrequest) and add in route file and use route classes.

        Please see attached file.

        On Thu, Jan 24, 2013 at 4:11 PM, Chris Cavanagh’s Blog wrote:

        > ** > Chris Cavanagh commented: “khan – I’m curious how the SQL query is > executed… Is that part of your site? Trying to understand how the routing > could be getting involved…” >

      2. HI Chris,

        Thanks for your help.

        I have found solution.

        I have added *System.Web.Routing.RouteTable.Routes.RouteExistingFiles = false; *in my global.asax file and it’s working fine now.

        Regards,

        Fahim

  109. Hi Chris,

    Thanks for your response.

    Please if you will find any solution then respond me.

    Now I am leaving for the day because I am in india and now here 10:15 PM.

    Thanks,
    Khan

    Reply

  110. Sir,
    your blog is really very interesting and helpful.

    FYI, I am Beginner in asp.net.
    I have created a demo to figure out how it works.
    I have implemented URL Routing like this,

    In Global.asax.cs,

    routes.Add( “ZoneTours”,
    new Route(“Webform.aspx/{HotelName}/{Id}”,
    new SiteRouteHandler() { PageVirtualPath = “~/WebForm1.aspx” })
    );

    In SiteRouteHandler.cs

    Page page;
    page = BuildManager.CreateInstanceFromVirtualPath(PageVirtualPath, typeof(Page)) as Page;
    foreach (var item in requestContext.RouteData.Values)
    {
    HttpContext.Current.Items[“qparam.” + item.Key] = item.Value;
    }
    return page;

    In Default.aspx.cs

    Response.Redirect(“~/Webform.aspx/John-Internationl/71579”);

    In WebForm1.aspx.cs

    Response.Write(“HotelName:- ” + Context.Items[“qparam.HotelName”].ToString());

    Response.Write(“HotelID:- ” + Context.Items[“qparam.Id”].ToString());

    My Url is

    “http://localhost:4396/Webform.aspx/Milan-Internationl/71579”

    Now, I have two questions.
    1st, Is it right, i mean will it give me best performance?

    2nd,
    My Url contain Name as well as id. I need id to get other details in ‘WebForm1.aspx.cs’ page and name to display in url. But i don’t wanna disclose id in url. How can i do it?

    Reply

    1. Bhautik – It’s best if a URL can contain enough information to uniquely identify what a page needs to display. The main benefit is a user can easily share the URL with someone else, without concerns about session state etc. Also it makes handling F5/refresh much simpler (again, no issues if session times out while visitor is reading the page). If the hotel name is unique enough, there’s maybe no need for the ID in your URL; you could simply query on the name in your code-behind. What’s the reason you don’t want the ID in there? If your IDs are Guids, you could use something like ShortGuid (http://www.singular.co.nz/blog/archive/2007/12/20/shortguid-a-shorter-and-url-friendly-guid-in-c-sharp.aspx) which looks much cleaner in a URL.

      Reply

Leave a reply to Abhinav Agrawal Cancel reply