我正在嘗試創建一個自動站點地圖ActionResult,它輸出一個有效的sitemap.xml文件。文件的實際生成不是問題,但我似乎無法弄清楚如何在系統中填充URL列表。這裏是我的代碼至今:ASP.NET MVC中的動態站點地圖
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);
}
}
舉例來說,假設我有兩個控制器,每個控制器具有與之相關聯的兩個動作:
HelpController
- 編輯
- 創建
AboutController
- 公司
- 管理
我似乎無法弄清楚如何獲得URL的喜歡的列表:
- http://localhost/help/edit
- http://localhost/help/create
- http://localhost/about/company
- http://localhost/about/management
最近,像@ eduncan911的回答一樣,最好的解決方案是使用http://mvcsitemap.codeplex.com/活動和更新的項目,支持安全修整並生成sitemap.xml。如果代理支持它,它也可以自動壓縮站點地圖,並且如果站點太大,則將站點地圖分割成子站點地圖,因爲sitemap.xml標準僅限於50k節點。 – CallMeLaNN 2011-03-16 17:14:51
感謝CallMeLaNN。我最近更新了答案,列出了這些要點以及更多內容,並列出了它轉移到的網站。 – eduncan911 2012-09-06 18:42:18