How to use Control.GetRouteUrl from a class in App_Code

非 Y 不嫁゛ 提交于 2019-12-04 12:43:29

问题


I'm using routing in asp.net web forms 4.0 with some success. In my pages I am using Page.GetRouteURL to generate routes like this.

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

This works perfectly well, but I have found that there are times when I need to have this functionality in a class in app_code. I could just manually build the route with String.Format, but that is kind of sloppy since it would duplicate the code in Global.asax that defines the routes.

Of course, there is no Page object in a class in App_Code, so I can't just call GetRouteUrl. Looking up in the docs on msdn I see somethingthat looks helpful.

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

So I followed the docs to this page which states that System.Web.Routing.GetVirtualPath() requires a System.Web.Routing.RequestContext object. I know about the HttpContext object, but I can't figure out what a RequestContext is. Anybody had any luck with this?


回答1:


RequestContext is available as a property to HttpRequest object, so you can refer it as HttpContext.Current.Request.RequestContext. For example,

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;
}


来源:https://stackoverflow.com/questions/5942018/how-to-use-control-getrouteurl-from-a-class-in-app-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!