(332) 331-8677

How to create dynamically sitemap.xml ASP.NET Core

Sitemap ASP.NET Core - Nuget - https://www.nuget.org/packages/SiteMapJR/

Usage example

using Site.Data;
using SiteMapJR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading.Tasks;

namespace Site.Controllers
{
    public class SitemapController : Controller
    {
        private readonly ApplicationDbContext _context;

        public SitemapController(ApplicationDbContext context)
        {
            _context = context;
        }

        [Route("sitemap")]
        public async Task<ActionResult> SitemapAsync()
        {
            string baseUrl = "https://site.com";

            var articles = await _context.Articles.ToListAsync();
            var catalogs = await _context.Catalogs.ToListAsync();

            var siteMapBuilder = new SitemapBuilder();

            siteMapBuilder.AddUrl(baseUrl, modified: DateTime.UtcNow, changeFrequency: ChangeFrequency.Weekly, priority: 1.0);
            siteMapBuilder.AddUrl($"{baseUrl}/prices", modified: null, changeFrequency: ChangeFrequency.Monthly, priority: 0.9);
            siteMapBuilder.AddUrl($"{baseUrl}/contacts", modified: null, changeFrequency: ChangeFrequency.Monthly, priority: 0.9);

            foreach (var item in articles)
            {
                siteMapBuilder.AddUrl($"{baseUrl}/articles/{item.Slug}", modified: item.Updated, changeFrequency: ChangeFrequency.Monthly, priority: 0.9);
            }
            foreach (var item in catalogs)
            {
                siteMapBuilder.AddUrl($"{baseUrl}/catalog/profil/{item.Slug}", modified: item.Updated, changeFrequency: ChangeFrequency.Yearly, priority: 0.9);
            }
            
            string xml = siteMapBuilder.ToString();
            return Content(xml, "text/xml");
        }
    }
}