2

如何使用 Razor 页面创建 XML(特别是我正在尝试构建 sitemap.xml)?

我读过 MSDN Introduction to Razor Pages但它只展示了如何创建 HTML 页面。当我只使用在 Razor中生成动态 XML 中所示的基本 XML 时,出现问题......

4

1 回答 1

9

添加具有以下内容的新 Razor 页面。

@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>

之前的 XML 声明@{Layout=null;}是必不可少的!否则 XML 解析器将无法正常工作,这一切都是徒劳的。

奖励:要使路由 /sitemap.xml 工作,您需要添加它。

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services
            .AddRazorPagesOptions(options => 
            {
                options.Conventions.AddPageRoute("/Sitemap", "sitemap.xml");
            });
    }
}
于 2017-11-22T16:24:42.813 回答