使用 ASP.NET MVC 中的路由和控制器自动生成 XML 站点地图

发布于 2024-08-13 09:28:05 字数 71 浏览 5 评论 0原文

是否可以通过迭代应用程序的路径和控制器操作来自动为搜索引擎生成 XML 站点地图?如果您能为我提供一个想法,我将不胜感激。谢谢。

would it be possible to generate a XML sitemap for search engines automatically by iterating the routes and the controllers' action of an applicacion? If you could provide me with an idea or so I would appreciate it. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我的痛♀有谁懂 2024-08-20 09:28:05

创建一个像这样的属性,并将其应用到您想要作为 sitemap.xml 文件中的页面的任何方法。

/// <summary>
/// This attribute indicates that a method is an actual page and gives the data for it
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MVCUrlAttribute : ActionFilterAttribute
{
    public string Url { get; private set; }

    public MVCUrlAttribute(string url)
    {
        this.Url = url;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        string fullyQualifiedUrl = filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + this.Url;
        // We build HTML here because we want the View to be easily able to include it without any conditionals
        // and because the ASP.NET WebForms view engine sometimes doesn’t subsitute <% in certain head items
        filterContext.Controller.ViewData["CanonicalUrl"] = @”<link rel=”"canonical”" href=”"” + fullyQualifiedUrl + ” />”;
        base.OnResultExecuting(filterContext);
    }
}

现在使用反射来查找所有这些“页面”:-

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

 // Find all the MVC Routes
 Log.Debug(“*** FINDING ALL MVC ROUTES MARKED FOR INCLUSION IN SITEMAP”);
 var allControllers = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)));
 Log.DebugFormat(“Found {0} controllers”, allControllers.Count());

 foreach (var controllerType in allControllers)
 {
     var allPublicMethodsOnController = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
     Log.DebugFormat(“Found {0} public methods on {1}”, allPublicMethodsOnController.Count(), controllerType.Name);

     foreach (var publicMethod in allPublicMethodsOnController)
     {
         var mvcurlattr = publicMethod.GetCustomAttributes(true).OfType<MVCUrlAttribute>().FirstOrDefault();
         if (mvcurlattr != null)
         {
             string url = mvcurlattr.Url;
             Log.Debug(“Found “ + controllerType.Name + “.” + publicMethod.Name + ” <– “ + url);
             allPageUrls.Add(url);
         }
     }
 }

现在从此列表构建 sitemap.xml 文件。

另请注意,ActionFilter 将规范 URL 放入您的视图模型中,以便您可以轻松地使所有页面搜索引擎友好,即使您有重复的内容。

您无法从路由执行此操作,因为整个应用程序 {controller}/{action} 可能只有一条路由。

更多信息请参见:- http://blog.abodit .com/2010/02/sitemap-xml-asp-net-aspnet-mvc/

Create an attribute like this and apply it to any methods that you want as pages in sitemap.xml file.

/// <summary>
/// This attribute indicates that a method is an actual page and gives the data for it
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MVCUrlAttribute : ActionFilterAttribute
{
    public string Url { get; private set; }

    public MVCUrlAttribute(string url)
    {
        this.Url = url;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        string fullyQualifiedUrl = filterContext.HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + this.Url;
        // We build HTML here because we want the View to be easily able to include it without any conditionals
        // and because the ASP.NET WebForms view engine sometimes doesn’t subsitute <% in certain head items
        filterContext.Controller.ViewData["CanonicalUrl"] = @”<link rel=”"canonical”" href=”"” + fullyQualifiedUrl + ” />”;
        base.OnResultExecuting(filterContext);
    }
}

Now use reflection to find all of those 'pages':-

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

 // Find all the MVC Routes
 Log.Debug(“*** FINDING ALL MVC ROUTES MARKED FOR INCLUSION IN SITEMAP”);
 var allControllers = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.IsSubclassOf(typeof(Controller)));
 Log.DebugFormat(“Found {0} controllers”, allControllers.Count());

 foreach (var controllerType in allControllers)
 {
     var allPublicMethodsOnController = controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
     Log.DebugFormat(“Found {0} public methods on {1}”, allPublicMethodsOnController.Count(), controllerType.Name);

     foreach (var publicMethod in allPublicMethodsOnController)
     {
         var mvcurlattr = publicMethod.GetCustomAttributes(true).OfType<MVCUrlAttribute>().FirstOrDefault();
         if (mvcurlattr != null)
         {
             string url = mvcurlattr.Url;
             Log.Debug(“Found “ + controllerType.Name + “.” + publicMethod.Name + ” <– “ + url);
             allPageUrls.Add(url);
         }
     }
 }

Now build the sitemap.xml file from this list.

Note also that the ActionFilter puts a canonical URL into your view model so you can easily make all your pages search engine friendly even if you have duplicate content.

You CANNOT do this from routes because you might have just one route for your entire application {controller}/{action}.

More here:- http://blog.abodit.com/2010/02/sitemap-xml-asp-net-aspnet-mvc/

微凉 2024-08-20 09:28:05

请查看 ASP.NET MVC SiteMap 提供程序 - MvcSiteMap

我自己没有使用过它,所以我不能保证它,但当我读到你的问题时,它确实浮现在我的脑海中。

HTH,
查尔斯

Have a gander at ASP.NET MVC SiteMap provider - MvcSiteMap.

I haven't used it myself so I can't vouch for it, but it did spring to mind when I read your question.

HTHs,
Charles

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文