SITEMAP IN ASP.NET MVC

john rob

Total Post:108

Points:756
Posted by  john rob
 1029  View(s)
Ratings:
Rate this:
'm trying to create an automatic sitemap ActionResult that outputs a valid sitemap.xml file. The actual generation of the file is not a problem, but I can't seem to figure out how to populate the list of URL's in the system. Here is the code I have so far:

public ContentResult Sitemap()

        {

            XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";

            XElement root = new XElement(xmlns + "urlset");

 

            using (MemoryStream ms = new MemoryStream())

            {

                using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8))

                {

                    root.Save(writer);

                }

 

                return Content(Encoding.UTF8.GetString(ms.ToArray()), "text/xml", Encoding.UTF8);

            }

        }

For instance, suppose I have two controllers, and each controller has two actions associated with them:

HelpController

·         Edit

·         Create

AboutController

·         Company

·         Management

 

  1. Kamlakar Singh

    Post:194

    Points:1396
    Re: Sitemap in Asp.Net MVC

    I took a look at Maarten Balliauw's approach per likwid's comment, but it seems to be overkill for what I'm trying to do.

    I've hacked together a temporary solution. I'm simply passing the controller and action names to generate the URL's. In order to generate the URL's, I'm using the following code:

        List<string> urlList = new List<string>();

        urlList.Add(GetUrl(new { controller = "Help", action = "Edit" }));

        urlList.Add(GetUrl(new { controller = "Help", action = "Create" }));

        urlList.Add(GetUrl(new { controller = "About", action = "Company" }));

        urlList.Add(GetUrl(new { controller = "About", action = "Management" }));

    where GetUrl is as below:

    protected string GetUrl(object routeValues)

            {

                RouteValueDictionary values = new RouteValueDictionary(routeValues);

                RequestContext context = new RequestContext(HttpContext, RouteData);

     

                string url = RouteTable.Routes.GetVirtualPath(context, values).VirtualPath;

     

                return new Uri(Request.Url, url).AbsoluteUri;

            }

    This seems to do the trick for now, though I do like the idea of having actionfilter's applied to certain actions that get pulled together automatically.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!