Create sitemap.xml as ASP.NET Core Razor Page

sitemap is a standalone page. On the razor page model, the ApplicationDbcontext is injected to work with the database.

Below code will generate XML string and return as ContentResult having ContentType = "application/xml"

Our page model code looks like as written below:

namespace Sample.Pages
{
  public class SitemapModel : PageModel
  {
    public readonly ApplicationDbContext dbContext;

    public SitemapModel(ApplicationDbContext dbContext)
    {
      this.dbContext = dbContext;
    }

    public IActionResult OnGet()
    {
      var pages = dbContext.Pages.ToList();
      StringBuilder sb = new StringBuilder();
      sb.Append("<?xml version='1.0' encoding='UTF-8' ?><urlset xmlns = 'http://www.sitemaps.org/schemas/sitemap/0.9'>");

      foreach (var page in pages)
      {
        string mDate = page.ModifiedDate.ToString("yyyy-MM-ddTHH:mm:sszzz");
        var url = $"https://www.snippset.com/{page.Title}";
        sb.Append("<url><loc>" + url + "</loc><lastmod>" + mDate + "</lastmod><changefreq>{page.Frequency}</changefreq><priority>{page.Priority}</priority></url>");
      }

      sb.Append("</urlset>");

      return new ContentResult
      {
        ContentType = "application/xml",
        Content = sb.ToString(),
        StatusCode = 200
      };
    }
  }
}

Comments