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:
Dynamically generating a sitemap means it's created every time it is requested meaning it's always up to date and accurately reflects the state of your site at that moment in time. Dynamically generating a sitemap is usually faster and requires less resources than writing to a static file.
A SiteMap object is a component of the ASP.NET site navigation infrastructure that provides access to read-only site map information for page and control developers using navigation and SiteMapDataSource controls.
This means sitemaps are updated automatically when you add, edit, or delete content. Therefore, there is no need to generate or rebuild the sitemaps in most cases.
I posted a do-it-yourself
answer down below. But here is a package that does it out of the box for MVC sites:
http://mvcsitemap.codeplex.com/ (<- old site, but with extensive documentation!)
https://github.com/maartenba/MvcSiteMapProvider/wiki (<- moved to new site, lacking some documentation, and not as active)
Note that it does a multitude of things:
All of the above points are controlled from the single mvc.sitemap XML file you edit and configure. I've used this in a number of projects now to do 2 or 3 of the above points. Have it all configurable in 1 place, and dynamically generated, is really nice.
Though I find the ability to create dynamic data providers a bit cumbersome (and grossly violates any type of IoC you wish to do), it does get the job done and scales nicely once you bypass their caching and use your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With