如何APP_ code使用Control.GetRouteUrl从类code、GetRouteUrl、Control

由网友(只对你撒娇)分享简介:我使用asp.net网络路由形成4.0取得了一些成功。在我的网页我使用的Page.GetRouteUrl产生这样的路线。I'm using routing in asp.net web forms 4.0 with some success. In my pages I am using Page.GetRouteU...

我使用asp.net网络路由形成4.0取得了一些成功。在我的网页我使用的Page.GetRouteUrl产生这样的路线。

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>

这工作得很好,但我发现有些时候我必须APP_ code类中的这个功能。我可以手动生成与的String.Format路线,但那是一种草率的,因为它会重复code在Global.asax中定义的路由。

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.

当然,还有一类在APP_ code无Page对象,所以我不能只是调用GetRouteUrl。看在MSDN上的文档我看到somethingthat看起来有帮助的。

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.

此方法提供了一种用于编码   方便。它相当于   调用   RouteCollection.GetVirtualPath(RequestContext的,   字符串,RouteValueDictionary)方法。

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

于是我跟着文档来此页面其中规定系统.Web.Routing.GetVirtualPath()需要一个System.Web.Routing.RequestContext对象。我知道的HttpContext对象,但我想不出什么的RequestContext是。任何人有任何运气与此?

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?

推荐答案

的RequestContext 可作为的属性以Htt的prequest对象,所以你可以参考它作为 HttpContext.Current。 Request.RequestContext 。例如,

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;
}
阅读全文

相关推荐

最新文章