asp.net mvc 给出url字符串如何获得对应的controller和action?

推荐图书

  • C#与.NET 4高级程序设计(第5版)


1个回答

最后的方法如下:

public ActionResult Index()
{
RouteValueDictionary kvd = GetRouteValue("Home/Index/5");
if (kvd == null)
{
Response.Write("没有匹配到任何路由!");
}
else
{
Response.Write("controller:" + kvd["controller"] + "
");
Response.Write("action:" + kvd["action"] + "
");
}
return View();
}
private RouteValueDictionary GetRouteValue(string url)
{
foreach (Route route in RouteTable.Routes)
{
var parsedRoute = RouteParser.Parse(route.Url);
var values = parsedRoute.Match(url, route.Defaults);
if (values != null)
return values;
}
return null;
}