我在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);
}
}
这样做可以确保访问该网站的所有网址都是小写的。我想遵循MVC模式并将其移动到可以全局应用于所有过滤器的过滤器。
这是正确的做法吗?我将如何为上述代码创建过滤器?
答案 0 :(得分:1)
我的意见 - 过滤器为时已晚,无法处理全局网址重写。但要回答关于如何创建动作过滤器的问题:
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());
}
}
HOWEVER ,我建议将此任务推送到IIS并使用重写规则。确保将URL Rewrite Module添加到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>