Return XML using a Razor Page?

Viewed 2112
1 Answers

Add a new Razor Page with the following contents.

@page
<?xml version="1.0" encoding="UTF-8" ?>
@{
    Layout = null;
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @*Include your static urls*@
    <url>
        <loc>https://example.com/my-static-page</loc>
    </url>
    @*Dynamically include pages generated from your database*@
    @foreach(var article in articles)
    {
        <url>
            <loc>https://example.com/article/@article.Url</loc>
            <lastmod>@article.Modified.ToString("yyyy-MM-dd")</lastmod>
        </url>
    }
    @*You get the idea*@
</urlset>

The XML declaration coming before the @{Layout=null;} is essential! Otherwise XML parsers won't work correctly and this will all be for nothing.

Bonus: To make the route /sitemap.xml work you'll need to add this.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddRazorPagesOptions(options => 
            {
                options.Conventions.AddPageRoute("/Sitemap", "sitemap.xml");
            });
    }
}
Related