【问题标题】:Create SiteMap in ASP.NET MVC在 ASP.NET MVC 中创建站点地图
【发布时间】:2015-01-29 10:04:29
【问题描述】:

我想为 ASP.NET MVC 站点创建站点地图。我写这段代码

[XmlRoot("urlset", Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
    public class Sitemap
    {
        private ArrayList _map;

        public Sitemap()
        {
            _map = new ArrayList();
        }

        [XmlElement("url")]
        public Location[] Locations
        {
            get
            {
                Location[] items = new Location[_map.Count];
                _map.CopyTo(items);
                return items;
            }
            set
            {
                if (value == null)
                    return;
                var items = (Location[])value;
                _map.Clear();
                foreach (Location item in items)
                    _map.Add(item);
            }
        }

        public int Add(Location item)
        {
            return _map.Add(item);
        }
    }

    public class Location
    {
        public enum EChangeFrequency
        {
            Always,
            Hourly,
            Daily,
            Weekly,
            Monthly,
            Yearly,
            Never
        }

        [XmlElement("loc")]
        public string Url { get; set; }

        [XmlElement("changefreq")]
        public EChangeFrequency? ChangeFrequency { get; set; }
        public bool ShouldSerializeChangeFrequency() { return ChangeFrequency.HasValue; }

        [XmlElement("lastmod")]
        public DateTime? LastModified { get; set; }
        public bool ShouldSerializeLastModified() { return LastModified.HasValue; }

        [XmlElement("priority")]
        public double? Priority { get; set; }
        public bool ShouldSerializePriority() { return Priority.HasValue; }
    }

    public class XmlResult : ActionResult
    {
        private readonly object _objectToSerialize;

        public XmlResult(object objectToSerialize)
        {
            _objectToSerialize = objectToSerialize;
        }

        public object ObjectToSerialize
        {
            get { return _objectToSerialize; }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (_objectToSerialize != null)
            {
                context.HttpContext.Response.Clear();
                var xs = new XmlSerializer(_objectToSerialize.GetType());
                context.HttpContext.Response.ContentType = "text/xml";
                xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize);
            }
        }
    }

并在NewsFeedController 中创建Sitemap 操作像这样

 public ActionResult Sitemap()
        {
            var sm = new Sitemap();
            sm.Add(new Location()
            {
                Url = string.Format("http://www.TechnoDesign.ir/Articles/{0}/{1}", 1, "SEO-in-ASP.NET-MVC"),
                LastModified = DateTime.UtcNow,
                Priority = 0.5D
            });
            return new XmlResult(sm);
        }

并在RouteConfig 中为 SiteMap 定义新路线,如下所示

 public static void RegisterRoutes(RouteCollection routes)
        {


            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                  "SiteMap_route", // Route name
                  "sitemap.xml", // URL with parameters
                  new { controller = "NewsFeed", action = "Sitemap", name = UrlParameter.Optional, area = "" }, // Parameter defaults
                   namespaces: new[] { "Web.Controllers" }
              );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                 namespaces: new[] { "Web.Controllers" }
            );

        }

但是当输入/sitemap.xml 时得到error 404

【问题讨论】:

    标签: asp.net-mvc url-routing asp.net-mvc-routing sitemap mvcsitemapprovider


    【解决方案1】:

    对于 MVC 4 及更高版本的 MvcSiteMapProvider,我们遇到了同样的问题。我们通过删除然后替换 web.config 文件中的UrlRoutingModule 解决了这个问题。

    <configuration>
      <system.webServer>
        <modules>
          <remove name="UrlRoutingModule-4.0" />
          <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" />
        </modules>
      </system.webServer>
    </configuration> 
    

    【讨论】:

      【解决方案2】:

      在 MVC 5 及更低版本(MVC 6 很好)中不允许创建以文件扩展名 (.xml) 结尾的路由,因此您需要在 Web.config 文件中添加以下行。

      <configuration>
        <system.webServer>
          <handlers>
            <add name="SitemapXml" path="sitemap.xml" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
          </handlers>
        </system.webServer>
      </configuration>

      【讨论】:

        猜你喜欢
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-07
        • 1970-01-01
        • 2012-04-07
        • 1970-01-01
        • 2011-08-21
        相关资源
        最近更新 更多