|
| 1 | +using DotnetSitemapGenerator; |
| 2 | +using DotnetSitemapGenerator.Serialization; |
| 3 | +using Microsoft.AspNetCore.Mvc.Infrastructure; |
| 4 | + |
| 5 | +namespace EssentialCSharp.Web.Helpers; |
| 6 | + |
| 7 | +public static class SitemapXmlHelpers |
| 8 | +{ |
| 9 | + private const string RootUrl = "https://essentialcsharp.com/"; |
| 10 | + |
| 11 | + public static void EnsureSitemapHealthy(List<SiteMapping> siteMappings) |
| 12 | + { |
| 13 | + var groups = siteMappings.GroupBy(item => new { item.ChapterNumber, item.PageNumber }); |
| 14 | + foreach (var group in groups) |
| 15 | + { |
| 16 | + try |
| 17 | + { |
| 18 | + SiteMapping result = group.Single(item => item.IncludeInSitemapXml); |
| 19 | + } |
| 20 | + catch (Exception ex) |
| 21 | + { |
| 22 | + throw new InvalidOperationException($"Sitemap error: Chapter {group.Key.ChapterNumber}, Page {group.Key.PageNumber} has more than one canonical link, or none: {ex.Message}", ex); |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + public static void GenerateAndSerializeSitemapXml(DirectoryInfo wwwrootDirectory, List<SiteMapping> siteMappings, ILogger logger, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) |
| 28 | + { |
| 29 | + GenerateSitemapXml(wwwrootDirectory, siteMappings, actionDescriptorCollectionProvider, out string xmlPath, out List<SitemapNode> nodes); |
| 30 | + XmlSerializer sitemapProvider = new(); |
| 31 | + sitemapProvider.Serialize(new SitemapModel(nodes), xmlPath, true); |
| 32 | + logger.LogInformation("sitemap.xml successfully written to {XmlPath}", xmlPath); |
| 33 | + } |
| 34 | + |
| 35 | + public static void GenerateSitemapXml(DirectoryInfo wwwrootDirectory, List<SiteMapping> siteMappings, IActionDescriptorCollectionProvider actionDescriptorCollectionProvider, out string xmlPath, out List<SitemapNode> nodes) |
| 36 | + { |
| 37 | + xmlPath = Path.Combine(wwwrootDirectory.FullName, "sitemap.xml"); |
| 38 | + DateTime newDateTime = DateTime.UtcNow; |
| 39 | + |
| 40 | + // Start with the root URL |
| 41 | + nodes = new() { |
| 42 | + new($"{RootUrl}") |
| 43 | + { |
| 44 | + LastModificationDate = newDateTime, |
| 45 | + ChangeFrequency = ChangeFrequency.Daily, |
| 46 | + Priority = 1.0M |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + // Add routes dynamically discovered from controllers (excluding Identity routes) |
| 51 | + var controllerRoutes = GetControllerRoutes(actionDescriptorCollectionProvider); |
| 52 | + foreach (var route in controllerRoutes) |
| 53 | + { |
| 54 | + nodes.Add(new($"{RootUrl.TrimEnd('/')}{route}") |
| 55 | + { |
| 56 | + LastModificationDate = newDateTime, |
| 57 | + ChangeFrequency = GetChangeFrequencyForRoute(route), |
| 58 | + Priority = GetPriorityForRoute(route) |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + // Add site mappings from content |
| 63 | + nodes.AddRange(siteMappings.Where(item => item.IncludeInSitemapXml).Select<SiteMapping, SitemapNode>(siteMapping => new($"{RootUrl}{siteMapping.Keys.First()}") |
| 64 | + { |
| 65 | + LastModificationDate = newDateTime, |
| 66 | + ChangeFrequency = ChangeFrequency.Daily, |
| 67 | + Priority = 0.8M |
| 68 | + })); |
| 69 | + } |
| 70 | + |
| 71 | + private static List<string> GetControllerRoutes(IActionDescriptorCollectionProvider actionDescriptorCollectionProvider) |
| 72 | + { |
| 73 | + var routes = new List<string>(); |
| 74 | + |
| 75 | + foreach (var actionDescriptor in actionDescriptorCollectionProvider.ActionDescriptors.Items) |
| 76 | + { |
| 77 | + // Skip Identity area routes |
| 78 | + if (actionDescriptor.RouteValues.TryGetValue("area", out var area) && area == "Identity") |
| 79 | + continue; |
| 80 | + |
| 81 | + // Skip the default fallback route (Index action in HomeController) |
| 82 | + if (actionDescriptor.RouteValues.TryGetValue("action", out var action) && action == "Index") |
| 83 | + continue; |
| 84 | + |
| 85 | + // Skip Error actions |
| 86 | + if (action == "Error") |
| 87 | + continue; |
| 88 | + |
| 89 | + // Get the route template or attribute route |
| 90 | + if (actionDescriptor.AttributeRouteInfo?.Template is string template) |
| 91 | + { |
| 92 | + // Clean up the template (remove parameters, etc.) |
| 93 | + var cleanRoute = template.TrimStart('/'); |
| 94 | + if (!string.IsNullOrEmpty(cleanRoute) && !routes.Contains($"/{cleanRoute}")) |
| 95 | + { |
| 96 | + routes.Add($"/{cleanRoute}"); |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + return routes.Distinct().OrderBy(r => r).ToList(); |
| 102 | + } |
| 103 | + |
| 104 | + private static ChangeFrequency GetChangeFrequencyForRoute(string route) |
| 105 | + { |
| 106 | + return route.ToLowerInvariant() switch |
| 107 | + { |
| 108 | + "/termsofservice" => ChangeFrequency.Yearly, |
| 109 | + "/announcements" => ChangeFrequency.Monthly, |
| 110 | + "/guidelines" => ChangeFrequency.Monthly, |
| 111 | + _ => ChangeFrequency.Monthly |
| 112 | + }; |
| 113 | + } |
| 114 | + |
| 115 | + private static decimal GetPriorityForRoute(string route) |
| 116 | + { |
| 117 | + return route.ToLowerInvariant() switch |
| 118 | + { |
| 119 | + "/home" => 0.5M, |
| 120 | + "/about" => 0.5M, |
| 121 | + "/announcements" => 0.5M, |
| 122 | + "/guidelines" => 0.9M, |
| 123 | + "/termsofservice" => 0.2M, |
| 124 | + _ => 0.5M |
| 125 | + }; |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +public class InvalidItemException : Exception |
| 130 | +{ |
| 131 | + public InvalidItemException(string? message) : base(message) |
| 132 | + { |
| 133 | + } |
| 134 | + public InvalidItemException(string? message, Exception exception) : base(message, exception) |
| 135 | + { |
| 136 | + } |
| 137 | +} |
0 commit comments