How to programmatically create a sitemap in Asp.net MVC 4?

by genevieve_boehm , in category: SEO , 9 months ago

How to programmatically create a sitemap in Asp.net MVC 4?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by chasity.halvorson , 7 months ago

@genevieve_boehm 

In ASP.NET MVC 4, you can programmatically generate a sitemap by creating a custom ActionResult and generating the XML structure of the sitemap.


Here's an example of how to do this:

  1. Create a new class called "SitemapResult" that inherits from ActionResult:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class SitemapResult : ActionResult
{
    private readonly List _nodes;

    public SitemapResult(List nodes)
    {
        _nodes = nodes;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "text/xml";

        // Generate the XML structure of the sitemap
        XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        XDocument xdoc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement(xmlns + "urlset",
                from node in _nodes
                select CreateUrlElement(xmlns, node)
            )
        );

        // Write the XML to the response stream
        using (var writer = new XmlTextWriter(context.HttpContext.Response.Output))
        {
            writer.Formatting = Formatting.Indented;
            xdoc.Save(writer);
        }
    }

    private XElement CreateUrlElement(XNamespace xmlns, SitemapNode node)
    {
        return new XElement(xmlns + "url",
            new XElement(xmlns + "loc", node.Url),
            new XElement(xmlns + "lastmod", node.LastModified.ToString("yyyy-MM-dd")),
            new XElement(xmlns + "changefreq", node.ChangeFrequency),
            new XElement(xmlns + "priority", node.Priority)
        );
    }
}


  1. Create a class called "SitemapNode" to represent each page in the sitemap:
1
2
3
4
5
6
7
public class SitemapNode
{
    public string Url { get; set; }
    public DateTime LastModified { get; set; }
    public string ChangeFrequency { get; set; }
    public decimal Priority { get; set; }
}


  1. In your MVC controller, generate the list of sitemap nodes and return the SitemapResult:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class SitemapController : Controller
{
    public ActionResult Index()
    {
        // Generate the list of sitemap nodes
        List nodes = new List
        {
            new SitemapNode
            {
                Url = Url.Action("Index", "Home", null, Request.Url.Scheme),
                LastModified = DateTime.Now,
                ChangeFrequency = "daily",
                Priority = 1.0m
            },
            // Add more nodes for other pages
        };

        return new SitemapResult(nodes);
    }
}


  1. Register the SitemapController in your RouteConfig.cs file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Add this line to register the SitemapController
    routes.MapRoute("Sitemap", "sitemap.xml", new { controller = "Sitemap", action = "Index" });

    // Add your other routes here

    // Set the default route
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}


Now, when you visit the URL "http://yourdomain.com/sitemap.xml", you will see the generated sitemap XML.


Note: Make sure to replace "yourdomain.com" with your actual domain name.