目前找到了2个开源库:
Simple sitemap generator for .NET
A minimalist library for creating sitemap files and also creating physical XML file
最终没有使用开源库,参考同事的代码用 XmlWriter
基于 ASP.NET Core Minimal API 实现了
public static class SitemapEndpoint
{
public const string MapPath = "/sitemap";
public const string ContentType = "text/xml; charset=utf-8";
public static void MapSitemapEndpoint(this IEndpointRouteBuilder app)
{
app.MapGet(MapPath, ProduceSitemapAsync);
}
private static async Task ProduceSitemapAsync(HttpContext context, IBlogQueryService blogQueryService)
{
context.Response.ContentType = ContentType;
await using var xml = XmlWriter.Create(context.Response.Body, new XmlWriterSettings { Async = true, Indent = true });
await xml.WriteStartDocumentAsync();
await xml.WriteStartElementAsync(null, "urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
foreach (var blogSite in blogSites)
{
var lastmod = blogSite.LastPublished.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sszzz");
await xml.WriteStartElementAsync(null, "url", null);
await xml.WriteElementStringAsync(null, "loc", null, blogSite.CanonicalUrl);
await xml.WriteElementStringAsync(null, "lastmod", null, lastmod);
await xml.WriteEndElementAsync();
}
await xml.WriteEndElementAsync();
await xml.WriteEndDocumentAsync();
}
}