Home > DeveloperSection > Forums > Sitemap in Asp.Net MVC
john rob

Total Post:108

Points:756
Posted on    October-10-2014 2:38 AM

 ASP.NET MVC ASP.Net  ASP.NET MVC 
Ratings:


 1 Reply(s)
 715  View(s)
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

 



Kamlakar Singh
Kamlakar Singh

Total Post:194

Points:1396
Posted on    October-10-2014 2:40 AM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick