首页 新闻 会员 周边

ASP.NET Core 中生成 sitemap 那个开源库好用

0
悬赏园豆:30 [已解决问题] 解决于 2024-01-28 21:30

目前找到了2个开源库:

Simple sitemap generator for .NET

A minimalist library for creating sitemap files and also creating physical XML file

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2024-01-28 10:42
< >
分享
最佳答案
0

最终没有使用开源库,参考同事的代码用 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();
    }
}
dudu | 高人七级 |园豆:30994 | 2024-01-28 21:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册