ASP.NET MVC:路线到URL [英] ASP.NET MVC: Route to URL
本文介绍了ASP.NET MVC:路线到URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是获取URL(相对或绝对)在MVC路由最简单的方法?我在这里看到了这个code对SO,但似乎有点冗长,不枚举RouteTable。
What's the easiest way to get the URL (relative or absolute) to a Route in MVC? I saw this code here on SO but it seems a little verbose and doesn't enumerate the RouteTable.
例如:
List<string> urlList = new List<string>();
urlList.Add(GetUrl(new { controller = "Help", action = "Edit" }));
urlList.Add(GetUrl(new { controller = "Help", action = "Create" }));
urlList.Add(GetUrl(new { controller = "About", action = "Company" }));
urlList.Add(GetUrl(new { controller = "About", action = "Management" }));
使用:
protected string GetUrl(object routeValues)
{
RouteValueDictionary values = new RouteValueDictionary(routeValues);
RequestContext context = new RequestContext(HttpContext, RouteData);
string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;
return new Uri(Request.Url, url).AbsoluteUri;
}
什么是更好的方式来检查RouteTable并获得一个给定的控制器和行动的网址?
What's a better way to examine the RouteTable and get a URL for a given controller and action?
推荐答案
这个怎么样(控制器):
How about this (in the controller):
public IEnumerable<SiteMapEntry> SiteMapEntries
{
get
{
var entries = new List<SiteMapEntry>();
foreach (var route in this.Routes)
{
entries.Add(new SiteMapEntry
(
this.Url.RouteUrl(route.Defaults),
SiteMapEntry.ChangeFrequency.Weekly,
DateTime.Now,
1F));
}
return entries;
}
}
当控制器成员:
public IEnumerable<Route> Routes
注意:
this.Url.RouteUrl(route.Defaults)
这篇关于ASP.NET MVC:路线到URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文