我正在尝试创建一个自动站点 map ActionResult,以输出有效的sitemap.xml文件。文件的实际生成不是问题,但是我似乎无法弄清楚如何在系统中填充URL列表。这是我到目前为止的代码:
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);
}
}
例如,假设我有两个 Controller ,并且每个 Controller 都有两个与之关联的 Action :
HelpController
关于 Controller
我似乎无法弄清楚如何获取类似URL的列表:
最佳答案
我在下面发布了do-it-yourself
答案。但是以下是针对MVC网站开箱即用的软件包:
http://mvcsitemap.codeplex.com/(
https://github.com/maartenba/MvcSiteMapProvider/wiki(
请注意,它可以做很多事情:
以上所有这些点都由您编辑和配置的单个mvc.sitemap XML文件控制。我现在在许多项目中都使用过此功能,可以完成上述两点或三点。将其全部配置在1个位置并动态生成,真的很棒。
尽管我发现创建动态数据提供程序的功能有点麻烦(并且严重违反了您希望做的任何类型的IoC),但确实可以完成工作并在绕过缓存并使用自己的扩展程序后可以很好地扩展。