Search code examples
asp.netwebformssystem.web.routing

Get the virtual url when using routing with webforms


How do I get the virtual url and not the webforms page name that the url is mapped to when using System.Web.Routing with webforms.

I want the url "/confirm/5" and not "Confirm.aspx".


Solution

  • To get the routed URL for the page you are currently visiting, use Request.Url, as Pavel notes.

    If you need to get the routed URL for a different page (such as when creating a hyperlink to another page), use the Page.GetRouteUrl method.

    Here's a code snippet showing the use of Page.GetRouteUrl. It's from my article, URL Routing in ASP.NET 4:

    lnkCategory.NavigateUrl = Page.GetRouteUrl("View Category", new { CategoryName = "Beverages" });

    In the above snippet, "View Category" is the name of the routing rule I want to use. CategoryName is one of the routing parameters and I want to use the value "Beverages". The above call to Page.GetRouteUrl returns the string "/Categories/Beverages". (Of course, the exact string is returns depends on the routing rule "View Category" and the parameter values, but hopefully you get the idea.)