我正在尝试找到一个很好的通用方法来规范化ASP.NET MVC 2应用程序中的URL。这是我到目前为止所提出的:
// Using an authorization filter because it is executed earlier than other filters
public class CanonicalizeAttribute : AuthorizeAttribute
{
public bool ForceLowerCase { get;set; }
public CanonicalizeAttribute()
: base()
{
ForceLowerCase = true;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
RouteValueDictionary values = ExtractRouteValues(filterContext);
string canonicalUrl = new UrlHelper(filterContext.RequestContext).RouteUrl(values);
if (ForceLowerCase)
canonicalUrl = canonicalUrl.ToLower();
if (filterContext.HttpContext.Request.Url.PathAndQuery != canonicalUrl)
filterContext.Result = new PermanentRedirectResult(canonicalUrl);
}
private static RouteValueDictionary ExtractRouteValues(AuthorizationContext filterContext)
{
var values = filterContext.RouteData.Values.Union(filterContext.RouteData.DataTokens).ToDictionary(x => x.Key, x => x.Value);
var queryString = filterContext.HttpContext.Request.QueryString;
foreach (string key in queryString.Keys)
{
if (!values.ContainsKey(key))
values.Add(key, queryString[key]);
}
return new RouteValueDictionary(values);
}
}
// Redirect result that uses permanent (301) redirect
public class PermanentRedirectResult : RedirectResult
{
public PermanentRedirectResult(string url) : base(url) { }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.RedirectPermanent(this.Url);
}
}
现在我可以这样标记我的控制器:
[Canonicalize]
public class HomeController : Controller { /* ... */ }
这一切似乎都运作得很好,但我有以下问题:
我仍然需要将CanonicalizeAttribute
添加到我想要规范化的每个控制器(或操作方法),当我很难想到我不想要这种行为的情况时。似乎应该有一种方法可以在整个站点范围内获得此行为,而不是一次只有一个控制器。
我在过滤器中实现'强制小写'规则的事实似乎是错误的。当然,最好以某种方式将其作为路由url逻辑,但我想不出在路由配置中这样做的方法。我想到将@"[a-z]*"
约束添加到控制器和操作参数(以及任何其他字符串路由参数),但我认为这将导致路由不匹配。此外,由于小写规则未在路由级别应用,因此可以在我的页面中生成包含大写字母的链接,这看起来非常糟糕。
我有什么明显的东西可以忽略吗?
答案 0 :(得分:19)
我对默认的ASP.NET MVC路由的轻松性质感到同样的“痒”,忽略了字母大小写,拖尾斜线等。像你一样,我想要一个解决问题的一般方法,最好是作为我的应用程序中的路由逻辑。
在搜索网络的高低之后,找不到有用的库,我决定自己滚动一个。结果是Canonicalize,一个开源类库,它补充了ASP.NET路由引擎。
您可以通过NuGet安装库:Install-Package Canonicalize
在您的路线注册中:routes.Canonicalize().Lowercase();
除了小写之外,包中还包含其他几种URL规范化策略。强制www
域前缀打开或关闭,强制使用特定主机名,尾部斜杠等。添加自定义URL规范化策略也很容易,我非常愿意接受补丁,为“添加更多策略”官方“ Canonicalize 发行。
我希望你或其他任何人都会觉得这很有帮助,即使问题是一年之久:)
答案 1 :(得分:7)
MVC 5和6可以选择为您的路线生成小写URL。我的路线配置如下所示:
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// Imprive SEO by stopping duplicate URL's due to case or trailing slashes.
routes.AppendTrailingSlash = true;
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
使用此代码,您不再需要规范化URL,因为这是为您完成的。如果您使用HTTP和HTTPS URL并且想要一个规范URL,则可能会出现一个问题。在这种情况下,使用上述方法并使用HTTPS替换HTTP非常容易,反之亦然。
另一个问题是链接到您网站的外部网站可能会忽略尾部斜杠或添加大写字符,为此您应该使用尾部斜杠执行301永久重定向到正确的URL。有关完整用法和源代码,请参阅我的blog post和RedirectToCanonicalUrlAttribute
过滤器:
/// <summary>
/// To improve Search Engine Optimization SEO, there should only be a single URL for each resource. Case
/// differences and/or URL's with/without trailing slashes are treated as different URL's by search engines. This
/// filter redirects all non-canonical URL's based on the settings specified to their canonical equivalent.
/// Note: Non-canonical URL's are not generated by this site template, it is usually external sites which are
/// linking to your site but have changed the URL case or added/removed trailing slashes.
/// (See Google's comments at http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
/// and Bing's at http://blogs.bing.com/webmaster/2012/01/26/moving-content-think-301-not-relcanonical).
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
public class RedirectToCanonicalUrlAttribute : FilterAttribute, IAuthorizationFilter
{
private readonly bool appendTrailingSlash;
private readonly bool lowercaseUrls;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RedirectToCanonicalUrlAttribute" /> class.
/// </summary>
/// <param name="appendTrailingSlash">If set to <c>true</c> append trailing slashes, otherwise strip trailing
/// slashes.</param>
/// <param name="lowercaseUrls">If set to <c>true</c> lower-case all URL's.</param>
public RedirectToCanonicalUrlAttribute(
bool appendTrailingSlash,
bool lowercaseUrls)
{
this.appendTrailingSlash = appendTrailingSlash;
this.lowercaseUrls = lowercaseUrls;
}
#endregion
#region Public Methods
/// <summary>
/// Determines whether the HTTP request contains a non-canonical URL using <see cref="TryGetCanonicalUrl"/>,
/// if it doesn't calls the <see cref="HandleNonCanonicalRequest"/> method.
/// </summary>
/// <param name="filterContext">An object that encapsulates information that is required in order to use the
/// <see cref="RedirectToCanonicalUrlAttribute"/> attribute.</param>
/// <exception cref="ArgumentNullException">The <paramref name="filterContext"/> parameter is <c>null</c>.</exception>
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.Ordinal))
{
string canonicalUrl;
if (!this.TryGetCanonicalUrl(filterContext, out canonicalUrl))
{
this.HandleNonCanonicalRequest(filterContext, canonicalUrl);
}
}
}
#endregion
#region Protected Methods
/// <summary>
/// Determines whether the specified URl is canonical and if it is not, outputs the canonical URL.
/// </summary>
/// <param name="filterContext">An object that encapsulates information that is required in order to use the
/// <see cref="RedirectToCanonicalUrlAttribute" /> attribute.</param>
/// <param name="canonicalUrl">The canonical URL.</param>
/// <returns><c>true</c> if the URL is canonical, otherwise <c>false</c>.</returns>
protected virtual bool TryGetCanonicalUrl(AuthorizationContext filterContext, out string canonicalUrl)
{
bool isCanonical = true;
canonicalUrl = filterContext.HttpContext.Request.Url.ToString();
int queryIndex = canonicalUrl.IndexOf(QueryCharacter);
if (queryIndex == -1)
{
bool hasTrailingSlash = canonicalUrl[canonicalUrl.Length - 1] == SlashCharacter;
if (this.appendTrailingSlash)
{
// Append a trailing slash to the end of the URL.
if (!hasTrailingSlash)
{
canonicalUrl += SlashCharacter;
isCanonical = false;
}
}
else
{
// Trim a trailing slash from the end of the URL.
if (hasTrailingSlash)
{
canonicalUrl = canonicalUrl.TrimEnd(SlashCharacter);
isCanonical = false;
}
}
}
else
{
bool hasTrailingSlash = canonicalUrl[queryIndex - 1] == SlashCharacter;
if (this.appendTrailingSlash)
{
// Append a trailing slash to the end of the URL but before the query string.
if (!hasTrailingSlash)
{
canonicalUrl = canonicalUrl.Insert(queryIndex, SlashCharacter.ToString());
isCanonical = false;
}
}
else
{
// Trim a trailing slash to the end of the URL but before the query string.
if (hasTrailingSlash)
{
canonicalUrl = canonicalUrl.Remove(queryIndex - 1, 1);
isCanonical = false;
}
}
}
if (this.lowercaseUrls)
{
foreach (char character in canonicalUrl)
{
if (char.IsUpper(character))
{
canonicalUrl = canonicalUrl.ToLower();
isCanonical = false;
break;
}
}
}
return isCanonical;
}
/// <summary>
/// Handles HTTP requests for URL's that are not canonical. Performs a 301 Permanent Redirect to the canonical URL.
/// </summary>
/// <param name="filterContext">An object that encapsulates information that is required in order to use the
/// <see cref="RedirectToCanonicalUrlAttribute" /> attribute.</param>
/// <param name="canonicalUrl">The canonical URL.</param>
protected virtual void HandleNonCanonicalRequest(AuthorizationContext filterContext, string canonicalUrl)
{
filterContext.Result = new RedirectResult(canonicalUrl, true);
}
#endregion
}
用法示例确保将所有请求301重定向到正确的规范URL:
filters.Add(new RedirectToCanonicalUrlAttribute(
RouteTable.Routes.AppendTrailingSlash,
RouteTable.Routes.LowercaseUrls));
答案 2 :(得分:5)
以下是我在MVC2中执行规范网址的方法。我使用IIS7重写模块v2使我的所有URL都小写,并删除尾部斜杠,所以不需要从我的代码中执行此操作。 (Full blog post)
将其添加到head部分的母版页中,如下所示:
<%=ViewData["CanonicalURL"] %>
<!--Your other head info here-->
创建过滤器属性(CanonicalURL.cs):
public class CanonicalURL : ActionFilterAttribute
{
public string Url { get; private set; }
public CanonicalURL(string url)
{
Url = url;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
string fullyQualifiedUrl = "http://www.example.com" + this.Url;
filterContext.Controller.ViewData["CanonicalUrl"] = @"<link rel='canonical' href='" + fullyQualifiedUrl + "' />";
base.OnResultExecuting(filterContext);
}
}
从您的操作中调用此方法:
[CanonicalURL("Contact-Us")]
public ActionResult Index()
{
ContactFormViewModel contact = new ContactFormViewModel();
return View(contact);
}
关于搜索引擎的其他一些有趣的文章相关帖子请查看Matt Cutts博客