Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return XML using a Razor Page?

How can I create an XML (in particular I'm trying to build sitemap.xml) using a Razor Page?

I've read MSDN Introduction to Razor Pages but it only shows how to create HTML pages. When I just use basic XML like shown in Generating dynamic XML in Razor something goes wrong...

like image 705
Licht Avatar asked Aug 17 '26 17:08

Licht


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");
            });
    }
}
like image 181
Licht Avatar answered Aug 19 '26 08:08

Licht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!