我正在尝试创建一个自动站点 map ActionResult,以输出有效的sitemap.xml文件。文件的实际生成不是问题,但是我似乎无法弄清楚如何在系统中填充URL列表。这是我到目前为止的代码:

    public ContentResult Sitemap()
    {
        XNamespace xmlns = "http://www.sitemaps.org/schemas/sitemap/0.9";
        XElement root = new XElement(xmlns + "urlset");

        //some kind of foreach here to get the loc variable for all URLs in the site
        //for each URL in the collection, add it to the root element as here

        //root.Add(
        //    new XElement("url",
        //        new XElement("loc", "http://google.com"),
        //        new XElement("changefreq", "daily")));

        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);
        }
    }

例如,假设我有两个 Controller ,并且每个 Controller 都有两个与之关联的 Action :

HelpController
  • 编辑
  • 创建

  • 关于 Controller
  • 公司
  • 管理

  • 我似乎无法弄清楚如何获取类似URL的列表:
  • http://localhost/help/edit
  • http://localhost/help/create
  • http://localhost/about/company
  • http://localhost/about/management
  • 最佳答案

    我在下面发布了do-it-yourself答案。但是以下是针对MVC网站开箱即用的软件包:

    http://mvcsitemap.codeplex.com/(
    https://github.com/maartenba/MvcSiteMapProvider/wiki(
    请注意,它可以做很多事情:

  • 自动将注册到Mvc路由中以响应SEO /sitemap.xml 请求(即使/sitemap.xml没有物理文件)。这与我发现的所有搜索引擎机器人完全兼容,并且在达到10,000时可以翻转等。
  • 带有一组局部 View ,可用于 BreadCrumb 内置导航!尽管动态数据部分有点麻烦,但我们确实广泛使用了它。
  • 带有一组用于控制Menu的局部 View 。
  • 遵循Controller和Action方法的[Authorize]安全位。

  • 以上所有这些点都由您编辑和配置的单个mvc.sitemap XML文件控制。我现在在许多项目中都使用过此功能,可以完成上述两点或三点。将其全部配置在1个位置并动态生成,真的很棒。

    尽管我发现创建动态数据提供程序的功能有点麻烦(并且严重违反了您希望做的任何类型的IoC),但确实可以完成工作并在绕过缓存并使用自己的扩展程序后可以很好地扩展。

    07-24 09:54
    查看更多