如何从 App_Code 中的类使用 Control.GetRouteUrl [英] How to use Control.GetRouteUrl from a class in App_Code

查看:26
本文介绍了如何从 App_Code 中的类使用 Control.GetRouteUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 asp.net web 表单 4.0 中使用路由并取得了一些成功.在我的页面中,我使用 Page.GetRouteURL 来生成这样的路由.

这非常有效,但我发现有时我需要在 app_code 的类中使用此功能.我可以使用 String.Format 手动构建路由,但这有点草率,因为它会复制 Global.asax 中定义路由的代码.

当然,App_Code的类中没有Page对象,所以不能直接调用GetRouteUrl.在 msdn 上的文档 中查找,我看到了一些看起来很有帮助的内容.<块引用>

这个方法是为编码提供的方便.它相当于调用RouteCollection.GetVirtualPath(RequestContext,String, RouteValueDictionary) 方法.

所以我按照文档到这个页面,其中指出系统.Web.Routing.GetVirtualPath() 需要一个 System.Web.Routing.RequestContext 对象.我知道 HttpContext 对象,但我不知道 RequestContext 是什么.有没有人有这方面的运气?

解决方案

RequestContext 可作为 HttpRequest 对象的一个​​属性,因此您可以将其称为 HttpContext.Current.Request.RequestContext.例如,

public string GetRouteUrl(string routeName, object routeParameters){var dict = new RouteValueDictionary(routeParameters);var data = RouteTable.Routes.GetVirtualPath(HttpContext.Current.Request.RequestContext, routeName, dict );如果(数据!= null){返回数据.虚拟路径;}返回空;}

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?

解决方案

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

这篇关于如何从 App_Code 中的类使用 Control.GetRouteUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆