问题描述:

I have the following code in the global.asax of my mvc web application:

/// <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);

}

}

What this achieves is to ensure all url's accessing the site are in lower case. I would like to follow the MVC pattern and move this to a filter that can applied globally to all filters.

Is this the correct approach? And how would I create a filter for the above code?

网友答案:

My opinion - a filter is too late to handle a global url rewrite. But to answer your question as to how, create an action filter:

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);
        }
    }
}

and in FilterConfig.cs, register your global filter:

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

HOWEVER, I would recommend pushing this task out to IIS and using a rewrite rule. Make sure the URL Rewrite Module is added to IIS and then add the following rewrite rule in your 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>
相关阅读:
Top