从路由集合中获取URL

时间:2014-10-21 06:39:43

标签: model-view-controller collections routes

我正在以这种格式加载到MVC项目多个路由上的路由集合:

 routes.MapRoute(
           name: string.Format("{0}/{1}/{2}/{3}", controller, action, seo.PageRefProductType, seo.PageRefProductId),
           url: seo.FriendlyUrl, 
           defaults: new { controller = controller, action = action, id=seo.PageRefProductId}
           );

当我使用API​​Controller访问它时,我可以使用Url.Route(派生自System.Web.Http.Routing.UrlHelper)来获取该路径中的友好URL。

我的问题是,当我没有Url.Route方法时,如何访问该URL,例如当我不在控制器中时。

这是我在global.asax上的应用启动:

  protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

        //loading the routes here:
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
        LocalSiteManager.UpdateLatestReviewInManagedData();

        //cache - Here is where I want to use the routes
        LocalWorkFlow.StaticCache.LoadStaticCache(RouteTable.Routes);

    }

这是我在LoadStaticCache中想要的:

public static void LoadStaticCache(RouteCollection routes)
{
    //get the URL of specific route by its' name
    string myUrl = routes["myUrlName"].Url;
}

1 个答案:

答案 0 :(得分:1)

我现在所做的是将每个路由名称和网址添加到Dictonary,其中我的密钥是路由名称,值是网址,然后我可以从我想要的任何地方访问它...