A sitemap is an XML file that contains all URLs of a website. When a website creates dynamic web pages, it is very difficult for Search Engines to search all URLs and index them. That is why we created a sitemap XML file and include all required URLs in it. It helps search engines find URLs easily and index them quickly.
The default URL is https://example.com/sitemap.xml
The sitemap.xml file must be encoded with UTF-8. Example of sitemap:
<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.example.com/</loc> <lastmod>2005-01-01</lastmod> <changefreq>monthly</changefreq> <priority>0.8</priority> </url> <!-- ... --> </urlset>
As you can see, each URL in a sitemap contains four pieces of metadata:
<urlset>
and ends with </urlset>
always
, hourly
, daily
, weekly
, monthly
, yearly
, never
). This gives search engines an indication of how often they should come back and re-index the page.The last three values only give search engines an indication of when they can or should index or even re-index a page. It is not a guarantee that it will happen, although it makes it more likely.
A sitemap is a standalone page. On the razor page model, the ApplicationDbcontext is injected to work with the database.
Below code will generate XML string and return as ContentResult having ContentType = "application/xml".
Our page model code looks like as written below:
namespace Sample.Pages
{
public class SitemapModel : PageModel
{
public readonly ApplicationDbContext dbContext;
public SitemapModel(ApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}
public IActionResult OnGet()
{
var pages = dbContext.Pages.ToList();
StringBuilder sb = new StringBuilder();
sb.Append("<?xml version='1.0' encoding='UTF-8' ?><urlset xmlns = 'http://www.sitemaps.org/schemas/sitemap/0.9'>");
foreach (var page in pages)
{
string mDate = page.ModifiedDate.ToString("yyyy-MM-ddTHH:mm:sszzz");
var url = $"https://www.snippset.com/{page.Title}";
sb.Append("<url><loc>" + url + "</loc><lastmod>" + mDate + "</lastmod><changefreq>{page.Frequency}</changefreq><priority>{page.Priority}</priority></url>");
}
sb.Append("</urlset>");
return new ContentResult
{
ContentType = "application/xml",
Content = sb.ToString(),
StatusCode = 200
};
}
}
}
ASP.NET Core provides the option to set a friendly URL. So instead of just sitemap, it can be set to sitemap.xml.
By using AddPageRoute the route to a page can be configured with a friendly URL.
options.Conventions.AddPageRoute("/Sitemap", "Sitemap.xml");
Further information for sitemap.xml