locked
Create Robots.txt and sitemap.xml dynamically in asp.net core RRS feed

  • Question

  • User2041008840 posted

    How can i create robots.txt and sitemap.xml in asp.net core when i start a project. 
    it will update automatically not need to change or replace the whole file. 
    this is just for seo. is it possible to create. 

    please help, 


    Thursday, October 24, 2019 7:22 AM

Answers

  • User-821857111 posted

    Normally, you create a view or page that generates XML for the site map from a data source.  The data source can be files on disk, content in a database etc. It depends on your project. You wouldn't actually start with an XML file. You could do that same thing with robots.txt - mapping the URL to a Razor Page, for example, that is designed to output text/plain. Here's an example Razor Page that could work as your sitemap:

    @page
    @model SitemapModel
    @{
        Layout = null;
    }
    <?xml version="1.0" encoding="utf-8" standalone="yes" ?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        @foreach (var item in Model.Items)
        {
        <url>
        <loc>@item.Url</loc>
        <lastmod>@item.LastModified.ToW3CDate()</lastmod>
        <changefreq>monthly</changefreq>
        </url>
        }
    </urlset>

    Model.Items is a collection of data that you want to display. The ToW3CDate method is an extension method that outputs a DateTime to a format that is valid for the Sitemap protocol:

    public static class DateTimeExtensions
    {
        public static string ToW3CDate(this DateTime dt)
        {
            return $"{dt.ToUniversalTime().ToString("s")}Z";
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 24, 2019 11:37 AM