是否可以通过迭代路由和控制器的应用操作来自动为搜索引擎生成XML站点地图?如果你能给我一个想法,我会很感激。感谢。
答案 0 :(得分:3)
创建这样的属性并将其应用于您想要作为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会将规范网址放入您的视图模型中,这样即使您有重复的内容,也可以轻松地使所有网页的搜索引擎都友好。
您不能从路线执行此操作,因为您的整个应用程序可能只有一条路线{controller} / {action}。
更多信息: - http://blog.abodit.com/2010/02/sitemap-xml-asp-net-aspnet-mvc/
答案 1 :(得分:1)