Skip to content

Instantly share code, notes, and snippets.

@DanDiplo DanDiplo/Sitemap.ashx Secret
Created May 31, 2015

Embed
What would you like to do?
<%@ WebHandler Language="C#" Class="Sitemap" %>
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web;
public class Sitemap : IHttpHandler
{
/* Generates an XML Sitemap for Umbraco using LinqToXml */
private static readonly XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
public void ProcessRequest(HttpContext context)
{
// Set correct headers from XML
context.Response.ContentType = "text/xml";
context.Response.Charset = "utf-8";
// Get the absolute base URL for this website
Uri url = HttpContext.Current.Request.Url;
string baseUrl = String.Format("{0}://{1}{2}",
url.Scheme, url.Host, url.IsDefaultPort ? String.Empty : ":" + url.Port);
// Create a new XDocument using namespace and add root element
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement urlset = new XElement(xmlns + "urlset");
UmbracoHelper umbHelper = new UmbracoHelper(UmbracoContext.Current);
// Get the root no
var rootNodes = umbHelper.TypedContentAtRoot().Where(n => n.TemplateId > 0);
// Iterate all nodes in site and add them to document
RecurseNodes(urlset, rootNodes, baseUrl);
doc.Add(urlset);
// Write XML document to response stream
context.Response.Write(doc.Declaration + "\n");
context.Response.Write(doc.ToString());
}
// Method to recurse all nodes and create each element
private static void RecurseNodes(XElement urlset, IEnumerable<IPublishedContent> nodes, string baseUrl)
{
foreach (IPublishedContent n in nodes)
{
if (n.TemplateId > 0)
{
string url = n.UrlAbsolute();
if (!url.StartsWith("http"))
{
url = baseUrl + url;
}
// Create the XML node
XElement urlNode = new XElement(xmlns + "url",
new XElement(xmlns + "loc", url),
new XElement(xmlns + "lastmod", n.UpdateDate.ToUniversalTime()));
urlset.Add(urlNode);
}
// Check if the node has any child nodes and, if it has, recurse them
if (n.Children() != null)
{
RecurseNodes(urlset, n.Children(), baseUrl);
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.