是否可以通过迭代路由和应用程序的 Controller 操作来自动为搜索引擎生成 XML 站点地图?如果你能给我一个想法,我将不胜感激。谢谢。
最佳答案
像这样创建一个属性并将其应用于您希望作为 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 放入您的 View 模型中,因此即使您有重复的内容,您也可以轻松地使所有页面搜索引擎友好。
您不能通过路由执行此操作,因为您的整个应用程序 {controller}/{action} 可能只有一个路由。
更多信息:- http://blog.abodit.com/2010/02/sitemap-xml-asp-net-aspnet-mvc/
关于asp.net-mvc - 使用 ASP.NET MVC 中的路由和 Controller 自动生成 XML 站点地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1835664/