Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a sitemap.xml in .NET core 2?

Can anyone tell me how to create a Sitemap in .NET Core 2?

These articles/alternate link are not working in .NET Core 2.

like image 756
Beginner Avatar asked May 12 '18 22:05

Beginner


People also ask

What is dynamic XML sitemap?

The dynamically generated XML Sitemap is created every time it is requested. This means it's always up to date and accurately reflects the state of your site at that moment in time. A dynamically generated file is usually faster to access than a static file.

How do I create a custom XML sitemap?

Go to SEO > General > Features. Make sure the “XML sitemaps” toggle is on. You should now see your sitemap (or sitemap index) at either yourdomain.com/sitemap.xml or yourdomain.com/sitemap_index.xml.

Are Sitemaps automatically generated?

Automatically generate a sitemap For sitemaps with more than a few dozen URLs, you will need to generate the sitemap. There are various tools that can generate a sitemap. However, the best way is to have your website software generate it for you.


2 Answers

Actually, I prefer to write it in a template file using Razor. Assuming you only have one page, A sample code in .NET Core 3.1 will look like this (.NET core 2 code won't be much different):

<!-- XmlSitemap.cshtml -->
@page "/sitemap.xml"
@using Microsoft.AspNetCore.Http
@{
    var pages = new List<dynamic>
    {
        new { Url = "http://example.com/", LastUpdated = DateTime.Now }
    };
    Layout = null;
    Response.ContentType = "text/xml";
    await Response.WriteAsync("<?xml version='1.0' encoding='UTF-8' ?>");
}

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    @foreach (var page in pages)
    {
        <url>
            <loc>@page.Url</loc>
            <lastmod>@page.LastUpdated.ToString("yyyy-MM-dd")</lastmod>
        </url>
    }
</urlset>

Hope this helps!

like image 168
Babak Avatar answered Oct 03 '22 00:10

Babak


Dynamic site map "sitemap-blog.xml" for Blog section and 24h cache. (ASP.NET Core 3.1)

  • sitemap.xml exists in wwwroot (generated by xml-sitemaps.com or ...).
  • sitemap-blog.xml generate dynamically.

robots.txt

User-agent: *
Disallow: /Admin/
Disallow: /Identity/
Sitemap: https://example.com/sitemap.xml
Sitemap: https://example.com/sitemap-blog.xml

Startup.cs

services.AddMemoryCache();

HomeController.cs

namespace MT.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IMemoryCache _cache;

        public HomeController(
            ApplicationDbContext context,
            IMemoryCache cache)
        {
            _context = context;
            _cache = cache;

        }

        [Route("/sitemap-blog.xml")]
        public async Task<IActionResult> SitemapBlog()
        {
            string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
            string segment = "blog";
            string contentType = "application/xml";

            string cacheKey = "sitemap-blog.xml";

            // For showing in browser (Without download)
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = cacheKey,
                Inline = true,
            };
            Response.Headers.Append("Content-Disposition", cd.ToString());

            // Cache
            var bytes = _cache.Get<byte[]>(cacheKey);
            if (bytes != null)
                return File(bytes, contentType);

            var blogs = await _context.Blogs.ToListAsync();

            var sb = new StringBuilder();
            sb.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");
            sb.AppendLine($"   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
            sb.AppendLine($"   xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">");

            foreach (var m in blogs)
            {
                var dt = m.LastModified;
                string lastmod = $"{dt.Year}-{dt.Month.ToString("00")}-{dt.Day.ToString("00")}";

                sb.AppendLine($"    <url>");

                sb.AppendLine($"        <loc>{baseUrl}/{segment}/{m.Slug}</loc>");
                sb.AppendLine($"        <lastmod>{lastmod}</lastmod>");
                sb.AppendLine($"        <changefreq>daily</changefreq>");
                sb.AppendLine($"        <priority>0.8</priority>");

                sb.AppendLine($"    </url>");
            }

            sb.AppendLine($"</urlset>");

            bytes = Encoding.UTF8.GetBytes(sb.ToString());

            _cache.Set(cacheKey, bytes, TimeSpan.FromHours(24));
            return File(bytes, contentType);
        }
    }
}
like image 45
Haddad Avatar answered Oct 03 '22 02:10

Haddad