0

我有一个 MVC 应用程序并填充路由表有这样的方法:

public static void RegisterRoutes(RouteCollection routes){
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    ....
   routes.MapRoute("default", "{controller}/{action}/{id}", new { controller = "Home", action = "index", id="" });
   ... etc
}

//and in global.asax it gets called like:
RegisterRoutes(RouteTable.Routes);

现在,如果我从 MVC 应用程序外部调用该方法(在某些控制台应用程序中,只是为了获取路由),我将传递一个新的空集合,它将填充 MVC 应用程序中使用的路由,但它有什么用呢?我可以仅基于路由集合,识别给定控制器名称、操作和其他参数的 url 吗?(再次,从网络应用程序的外部)

4

2 回答 2

0

我还希望能够从控制台应用程序(站点地图生成器)中的路由集合生成 url,并且有太多的路由来做简单的替换。我最终写了一个围绕 UrlHelper.GenerateUrl 的包装器......

public class UrlGenerator
{
    protected string Protocol;
    protected string HostName;
    protected RequestContext RequestContext;
    public RouteCollection RouteCollection;

    public UrlGenerator(string protocol, string hostName, Action<RouteCollection> registerRoutes)
    {
        Protocol = protocol;
        HostName = hostName;
        RouteCollection = new RouteCollection();
        registerRoutes(RouteCollection);
        // Construct a request context with as little as possible
        RequestContext = new RequestContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://x.com", null), new HttpResponse(null))), new RouteData());
    }

    public string GetUrl(string action, string controller, object routeData)
    {
        return GetUrl(action, controller, new RouteValueDictionary(routeData));
    }
    public string GetUrl(string action, string controller, RouteValueDictionary routeData)
    {
        return UrlHelper.GenerateUrl(null, action, controller, Protocol, HostName, null, routeData, RouteCollection, RequestContext, false);
    }
}

现在你可以做...

UrlGenerator g = new UrlGenerator("https", "myurl.com", RouteConfig.RegisterRoutes);
Console.WriteLine(g.GetUrl("Index", "Home", new { product = "toad-for-oracle" }));
于 2013-12-10T18:53:00.797 回答
0

我认为 routes[0].GetVirtualPath() 是您正在寻找的。但是,您必须将 RequestContext 和 RouteValueDictionary 传递给它。如果路由无法处理您的输入,它将返回 null

于 2013-01-24T22:12:44.600 回答