Skip to content

Instantly share code, notes, and snippets.

@garpunkal
Created January 8, 2020 10:25
Show Gist options
  • Save garpunkal/2b9b21bfe167b1de5d288ec5ccfda4b1 to your computer and use it in GitHub Desktop.
Save garpunkal/2b9b21bfe167b1de5d288ec5ccfda4b1 to your computer and use it in GitHub Desktop.
Sitemap.cs
public class XmlSitemap : IHttpHandler
{
public bool IsReusable => false;
private static readonly XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
public void ProcessRequest(HttpContext context)
{
string language = context.Request?.QueryString["language"]?.ToFriendlyUrlFormat();
context.Response.ContentType = "text/xml";
context.Response.Charset = "utf-8";
var cacheKey = new StringBuilder(ConfigurationManager.AppSettings["CachePrefix"]);
cacheKey.Append(HttpContext.Current.Request.Url.ToString().ToFriendlyUrlFormat());
var doc = (XDocument)ApplicationContext.Current?.ApplicationCache.RuntimeCache.GetCacheItem(
cacheKey.ToString().ToLower(),
() => CreateSitemap(language));
if (doc == null)
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
context.Response.End();
return;
}
context.Response.Write(doc.Declaration + "\n");
context.Response.Write(doc.ToString());
}
private static XDocument CreateSitemap(string language)
{
Uri url = HttpContext.Current.Request.Url;
string baseUrl = $"{url.Scheme}://{url.Host}{(url.IsDefaultPort ? string.Empty : ":" + url.Port)}";
XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement urlset = new XElement(xmlns + "urlset");
var homepage = GetHomepage(HttpContext.Current.Request.RequestContext, UmbracoContext.Current);
if (homepage == null)
return null;
var homepageChildren = homepage?.Children(x => x.IsVisible() && x.DocumentTypeAlias != "dataRepository");
RecurseNodes(urlset, homepageChildren, baseUrl);
doc.Add(urlset);
return doc;
}
private static IPublishedContent GetHomepage(RequestContext requestContext, UmbracoContext umbracoContext)
{
var helper = new UmbracoHelper(umbracoContext);
IPublishedContent homepage = helper.TypedContentAtRoot()
.FirstOrDefault(x => x.DocumentTypeAlias == "homepage" && x.IsVisible());
return homepage;
}
private static void RecurseNodes(XElement urlset, IEnumerable<IPublishedContent> nodes, string baseUrl)
{
if (nodes == null) return;
foreach (IPublishedContent n in nodes)
{
if (n.TemplateId > 0 && n.IsVisible())
{
string url = n.UrlAbsolute();
if (!url.StartsWith("https"))
url = baseUrl + url;
XElement urlNode = new XElement(xmlns + "url",
new XElement(xmlns + "loc", url),
new XElement(xmlns + "lastmod", n.UpdateDate.ToUniversalTime()));
urlset.Add(urlNode);
}
if (n.Children() != null)
RecurseNodes(urlset, n.Children(), baseUrl);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment