2

我的 mvc Web 应用程序的 global.asax 中有以下代码:

/// <summary>
    /// Handles the BeginRequest event of the Application control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // ensure that all url's are of the lowercase nature for seo
        string url = Request.Url.ToString();
        if (Request.HttpMethod == "GET" && Regex.Match(url, "[A-Z]").Success)
        {
            Response.RedirectPermanent(url.ToLower(CultureInfo.CurrentCulture), true);
        }
    }

这样做的目的是确保所有访问站点的 url 都是小写的。我想遵循 MVC 模式并将其移至可以全局应用于所有过滤器的过滤器。

这是正确的方法吗?以及如何为上述代码创建过滤器?

4

1 回答 1

1

我的意见 - 过滤器为时已晚,无法处理全局 url 重写。但是要回答您关于如何操作的问题,请创建一个操作过滤器:

public class LowerCaseFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // ensure that all url's are of the lowercase nature for seo
        var request = filterContext.HttpContext.Request;
        var url = request.Url.ToString();
        if (request.HttpMethod == "GET" && Regex.Match(url, "[A-Z]").Success)
        {
            filterContext.Result = new RedirectResult(url.ToLower(CultureInfo.CurrentCulture), true);
        }
    }
}

并在 FilterConfig.cs 中注册您的全局过滤器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute()); 
        filters.Add(new LowerCaseFilterAttribute());
    }
}

但是,我建议将此任务推送到 IIS 并使用重写规则。确保将URL 重写模块添加到 IIS,然后在 web.config 中添加以下重写规则:

<!-- http://ruslany.net/2009/04/10-url-rewriting-tips-and-tricks/ -->
<rule name="Convert to lower case" stopProcessing="true">
    <match url=".*[A-Z].*" ignoreCase="false" />
    <conditions>
        <add input="{REQUEST_METHOD}" matchType="Pattern" pattern="GET" ignoreCase="false" />
    </conditions>
    <action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />
</rule>
于 2013-01-05T05:07:48.190 回答