How to use Control.GetRouteUrl from a class in App_Code

I use asp.net 4.0 web form routing with some success. On my pages, I use Page.GetRouteURL to create such routes.

<a href = '<%=GetRouteUrl("MyRoute", new {MyFirstRouteValue = "ABC", MySecondRouteValue=123}) #>' >Link Text</a>

This works fine, but I found that there are times when I need to have this functionality in the class in app_code. I could just manually build the route using String.Format, but this is a bit sloppy as it will duplicate the code in Global.asax that defines the routes.

Of course, there is no Object in the App_Code class, so I can't just call GetRouteUrl. Looking in the docs on msdn I see something that looks useful.

This method is provided for coding convenience. This is equivalent to calling RouteCollection.GetVirtualPath (RequestContext, String, RouteValueDictionary).

So, I followed the docs on this page , which says that System.Web.Routing.GetVirtualPath () requires System.Web.Routing. RequestContext object. I know about the HttpContext object, but I can not understand what RequestContext is. Is anyone lucky with this?

+5
source share
1 answer

RequestContextis available as a property for the HttpRequest object, so you can refer to it as HttpContext.Current.Request.RequestContext. For instance,

public string GetRouteUrl(string routeName, object routeParameters)
{
   var dict = new RouteValueDictionary(routeParameters);
    var data = RouteTable.Routes.GetVirtualPath(HttpContext.Current.Request.RequestContext, routeName, dict );
    if (data != null)
    {
        return data.VirtualPath;
    }
    return null;
}
+9
source

All Articles