如何在ASP.NET MVC应用程序中正确地规范化URL?

12

我正在尝试找到一种在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 { /* ... */ }

这似乎都工作得相当好,但我有以下几个问题:

  1. 我仍然需要将 CanonicalizeAttribute 添加到我想要规范化的每个控制器(或操作方法)中,但很难想到不想要此行为的情况。似乎应该有一种方法可以在整个站点范围内获得此行为,而不是逐个控制器。

  2. 在过滤器中实现“强制小写”规则似乎是错误的。肯定有更好的方法将其合并到路由 URL 逻辑中,但是我想不出如何在我的路由配置中实现。我考虑为控制器和操作参数(以及任何其他字符串路由参数)添加 @"[a-z]*" 约束,但我认为这会导致路由无法匹配。而且,因为小写规则未在路由级别应用,所以可能会在页面中生成带有大写字母的链接,这似乎相当糟糕。

是否有什么明显的问题我忽略了?


1
有一种方法可以通过全局过滤器在MVC3中实现站点范围内的操作,但在不到MVC3的版本中,您需要创建一个基本控制器,将属性应用于该控制器,并从中派生所有控制器。不过,我必须问一下这样做的用例是什么? - Russ Cam
1
SEO。确保从格式不正确的链接进入的蜘蛛被重定向(永久性)到正确的链接 - 小写只是一个附带说明。http://en.wikipedia.org/wiki/Canonicalization#Search_Engines_and_SEO - Bennor McCarthy
3个回答

20

我也感受到了默认的ASP.NET MVC路由的宽松特性,忽略大小写、尾随斜杠等问题。和你一样,我想要一个通用的解决方案,最好是作为我的应用程序路由逻辑的一部分。

在高低点上搜索了一圈,没找到有用的库,于是我决定自己动手。结果是 Canonicalize ,这是一个开源的类库,可以补充 ASP.NET 路由引擎。

你可以通过 NuGet 安装这个库: Install-Package Canonicalize

然后在你的路由注册中添加以下内容:routes.Canonicalize().Lowercase();

除了小写字母,包含在该软件包中的还有几种其他 URL 规范化策略。强制使用或禁止 www 域前缀、指定主机名、尾随斜杠等。同时,很容易添加自定义URL规范化策略,我非常乐意接受补丁,将更多的策略添加到“官方”Canonicalize发行版中。

希望你或其他人会觉得这个对你有帮助,即使这个问题已经一年了 :)


1
肯定会去检查它。 - Bennor McCarthy
1
非常适合将重定向到与SSL证书匹配的主机名 - 谢谢 - fiat
1
优秀的库,正是我所寻找的。谢谢。 - Martin Hansen Lennox

10

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,则可能会出现问题。在这种情况下,很容易使用上述方法,将HTTP替换为HTTPS或反之亦然。
另一个问题是外部网站链接到您的站点时可能省略尾随斜杠或添加大写字符,为此,您应该对正确的URL执行301永久重定向,并在末尾添加斜杠。有关完整用法和源代码,请参阅我的博客文章 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));

1
为什么应该使用授权过滤器而不是操作过滤器?培根之所以不是火腿肉,是有原因的。 - Professor of programming
1
IAuthorizationFilter 是正确的选择。请参考这个答案。该过滤器在请求管道中较早执行。如果我们要重定向用户,最好尽早执行。 - Muhammad Rehan Saeed
这并没有说明何时应该使用授权过滤器而不是操作过滤器。我认为在这种情况下我们应该同意各自保留自己的观点。 - Professor of programming
好的。RequireHttpsAttribute也使用IAuthorizationFilter来执行重定向。这是性能与命名之间的权衡,由开发人员决定他们更喜欢哪个。 - Muhammad Rehan Saeed
这是因为它涉及到安全问题。而你的规范化URL重定向并不会产生相关作用。 - Professor of programming

6
以下是我在MVC2中处理规范URL的方法。我使用IIS7重写模块v2将所有URL转换为小写,并删除尾部斜杠,因此不需要从代码中执行此操作。(完整博客文章请按以下方式将其添加到主页面的头部:
<%=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博客。


1
我猜这里有一个错误。看看SO,如果在URL中编辑标题仍然会重定向到这里。使用您的代码,我猜它会呈现一个错误的URL。无论路径如何,SO都会呈现相同的内容。 - BrunoLM
1
URL是从操作中注入的。它的作用不是重定向,而是指示这是该资源的主要URL。 - Andrew
1
我喜欢这个想法,比起尝试从路由或某些黑客方式自动确定它要整洁得多。+1 AAA 会再次评论。 - Andrew Bullock
1
感谢您的评论,希望它在某种程度上有所帮助! :) - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接