怎样才可以有小写在ASP.NET MVC路线? [英] How can I have lowercase routes in ASP.NET MVC?
问题描述
我怎么能有小写,再加上如果可能的话强调,在ASP.NET MVC路线?所以,我将有 /晚宴/信息/ 2
通话 DinnersController.Details(2)
,如果可能, /晚宴/ more_details / 2
通话 DinnersController.MoreDetails(2)
?
How can I have lowercase, plus underscore if possible, routes in ASP.NET MVC? So that I would have /dinners/details/2
call DinnersController.Details(2)
and, if possible, /dinners/more_details/2
call DinnersController.MoreDetails(2)
?
这一切,同时仍使用类似模式{控制器} / {行动} / {ID}
。
All this while still using patterns like {controller}/{action}/{id}
.
推荐答案
通过System.Web.Routing 4.5,你可以通过设置RouteCollection的LowercaseUrls财产实现这个简单的:
With System.Web.Routing 4.5 you may implement this straightforward by setting LowercaseUrls property of RouteCollection:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
此外假设您是要重定向传入的URL为小写SEO的理由这样做(在许多过这篇文章的链接说的)。
Also assuming you are doing this for SEO reasons you want to redirect incoming urls to lowercase (as said in many of the links off this article).
protected void Application_BeginRequest(object sender, EventArgs e)
{
//You don't want to redirect on posts, or images/css/js
bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
if (isGet && HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false)
{
string lowercaseURL = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
if (Regex.IsMatch(lowercaseURL, @"[A-Z]"))
{
//You don't want to change casing on query strings
lowercaseURL = lowercaseURL.ToLower() + HttpContext.Current.Request.Url.Query;
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", lowercaseURL);
Response.End();
}
}
}
这篇关于怎样才可以有小写在ASP.NET MVC路线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!