A sitemap is good for SEO because it tells search engines what pages of your site it should index. But how do we create a sitemap in ASP.NET Core? In this post I will show you a very simple way to generate a sitemap that works in ASP.NET MVC and ASP.NET Core web projects.
Sample XML Sitemap
The following sample XML Sitemap is what we need to return when we visit
http://www.simple.com/sitemap
We can accomplish this in three easy steps.
Step 1: Create a SitemapUrl object
First we need to create a SitemapUrl
object to hold information about each page URL.
Step 2: Create the SitemapBuilder class
The next step is to create a SitemapBuilder
class that our MVC application can use to construct the sitemap.
Note: The following reference needs added to your project.json file for the code above to work in ASP.NET Core.
Step 3: Generating the Sitemap in ASP.NET Core by creating a SitemapController
The following example shows how the SitemapBuilder
can be used from an ASP.NET Core project.
As you can see from the code above, the SitemapBuilder
works similar to a StringBuilder
in that each URL is added via the AddUrl
method and then the XML Sitemap is generated using the final call to ToString
.
This is a very simple way of generating a sitemap for a simple use case (it’s how the sitemap for this site is generated). There are many improvements that could be made like creating a SitemapAttribute
and splitting the Sitemap into multiple pages but this sample is good enough for simple applications.
sample sitemap.xml
https://www.hijk.pw/sitemap_index.xml
https://www.iaspnetcore.com/sitemap.xml