我有一个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应用程序中使用的路由,但是&# 39;使用它? 我可以仅基于路线的集合,识别给定控制器名称,操作和其他参数的URL吗? (再次,从网络应用程序的外部)
答案 0 :(得分:0)
我认为您正在寻找路线[0] .GetVirtualPath()。但是,您必须将RequestContext和RouteValueDictionary传递给它。如果路由无法处理您的输入,则它将返回null
答案 1 :(得分: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" }));