在ASP.NET MVC的动态站点地图 [英] Dynamic sitemap in ASP.NET MVC
问题描述
我试图创建一个自动的站点地图的ActionResult,输出有效sitemap.xml的文件。该文件的实际发电不是一个问题,但我似乎无法弄清楚如何填充系统的URL列表。这里是code我到目前为止有:
I'm trying to create an automatic sitemap ActionResult that outputs a valid sitemap.xml file. The actual generation of the file is not a problem, but I can't seem to figure out how to populate the list of URL's in the system. Here is the code I have so far:
public ContentResult Sitemap()
{
XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XElement root = new XElement(xmlns + "urlset");
//some kind of foreach here to get the loc variable for all URLs in the site
//for each URL in the collection, add it to the root element as here
//root.Add(
// new XElement("url",
// new XElement("loc", "http://google.com"),
// new XElement("changefreq", "daily")));
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8))
{
root.Save(writer);
}
return Content(Encoding.UTF8.GetString(ms.ToArray()), "text/xml", Encoding.UTF8);
}
}
例如,假设我有两个控制器,每个控制器具有与之相关联的两个动作:
For instance, suppose I have two controllers, and each controller has two actions associated with them:
HelpController
- 编辑
- 创建
AboutController
- 公司
- 管理
我似乎无法弄清楚如何获得的名单网址,如:
I can't seem to figure out how to get a list of URL's like:
- http://localhost/help/edit
- http://localhost/help/create
- http://localhost/about/company
- http://localhost/about/management
推荐答案
我接过来一看,每likwid的评论马腾Balliauw的方法,但它似乎是矫枉过正我想要做的。
I took a look at Maarten Balliauw's approach per likwid's comment, but it seems to be overkill for what I'm trying to do.
我一起砍死一个临时解决方案。我只是通过控制器和动作名称生成URL的。为了生成URL的,我用下面的code:
I've hacked together a temporary solution. I'm simply passing the controller and action names to generate the URL's. In order to generate the URL's, I'm using the following code:
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" }));
其中的getURL是如下:
where GetUrl is as below:
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;
}
这似乎这样的伎俩现在,虽然我不喜欢有actionfilter的应用到自动获得拉到一起某些行动的想法。
This seems to do the trick for now, though I do like the idea of having actionfilter's applied to certain actions that get pulled together automatically.
这篇关于在ASP.NET MVC的动态站点地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!