如何在ASP.NET MVC中使用小写字母,如果可能的话加下划线?这样我就可以/dinners/details/2
打电话了DinnersController.Details(2)
,如果可能的话,/dinners/more_details/2
打电话DinnersController.MoreDetails(2)
吗?
所有这一切仍在使用诸如的模式{controller}/{action}/{id}
。
如何在ASP.NET MVC中使用小写字母,如果可能的话加下划线?这样我就可以/dinners/details/2
打电话了DinnersController.Details(2)
,如果可能的话,/dinners/more_details/2
打电话DinnersController.MoreDetails(2)
吗?
所有这一切仍在使用诸如的模式{controller}/{action}/{id}
。
Answers:
使用System.Web.Routing 4.5,您可以通过设置RouteCollection的LowercaseUrls属性来实现这一简单操作:
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 }
);
}
另外,假设您出于SEO的原因执行此操作,您希望将传入的URL重定向为小写字母(如本文中许多链接所述)。
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();
}
}
}
当我想做同样的事情并很好地工作时,这两个教程会有所帮助:
http://www.coderjournal.com/2008/03/force-mvc-route-url-lowercase/ http://goneale.com/2008/12/19/lowercase-route-urls-in-aspnet-mvc/
编辑:对于具有区域的项目,您需要修改GetVirtualPath()方法:
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
var lowerCaseValues = new RouteValueDictionary();
foreach (var v in values)
{
switch (v.Key.ToUpperInvariant())
{
case "ACTION":
case "AREA":
case "CONTROLLER":
lowerCaseValues.Add(v.Key, ((string)v.Value).ToLowerInvariant());
break;
default:
lowerCaseValues.Add(v.Key.ToLowerInvariant(), v.Value);
break;
}
}
return base.GetVirtualPath(requestContext, lowerCaseValues);
}
如果您碰巧使用了ASP.NET Core,则可能应该看看以下内容:
将以下行添加到该类的
ConfigureServices
方法Startup
。services.AddRouting(options => options.LowercaseUrls = true);
我是在Nick Berardi的Coder Journal上找到的,但是它没有有关如何实施LowercaseRoute
该类的信息。因此,请在此处重新发布其他信息。
首先将Route
课程扩展到LowercaseRoute
public class LowercaseRoute : Route
{
public LowercaseRoute(string url, IRouteHandler routeHandler)
: base(url, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
: base(url, defaults, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, IRouteHandler routeHandler)
: base(url, defaults, constraints, routeHandler) { }
public LowercaseRoute(string url, RouteValueDictionary defaults, RouteValueDictionary constraints, RouteValueDictionary dataTokens, IRouteHandler routeHandler) : base(url, defaults, constraints, dataTokens, routeHandler) { }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
VirtualPathData path = base.GetVirtualPath(requestContext, values);
if (path != null)
path.VirtualPath = path.VirtualPath.ToLowerInvariant();
return path;
}
}
然后修改RegisterRoutes
Global.asax.cs 的方法
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new LowercaseRoute("{controller}/{action}/{id}",
new RouteValueDictionary(new { controller = "Home", action = "Index", id = "" }),
new MvcRouteHandler()));
//routes.MapRoute(
// "Default", // Route name
// "{controller}/{action}/{id}", // URL with parameters
// new { controller = "Home", action = "Index", id = "" } // Parameter defaults
//);
}
但是我想知道一种使用routes.MapRoute的方法...
routes.MapRouteLowercase(...
比上述更好:goneale.wordpress.com/2008/12/19/...
您可以通过添加此类作为RouteCollection的扩展来继续使用MapRoute语法:
public static class RouteCollectionExtension
{
public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults)
{
return routes.MapRouteLowerCase(name, url, defaults, null);
}
public static Route MapRouteLowerCase(this RouteCollection routes, string name, string url, object defaults, object constraints)
{
Route route = new LowercaseRoute(url, new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints)
};
routes.Add(name, route);
return route;
}
}
现在,您可以在应用程序的启动中使用“ MapRouteLowerCase”代替“ MapRoute”:
public void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Url shortcuts
routes.MapRouteLowerCase("Home", "", new { controller = "Home", action = "Index" });
routes.MapRouteLowerCase("Login", "login", new { controller = "Account", action = "Login" });
routes.MapRouteLowerCase("Logout", "logout", new { controller = "Account", action = "Logout" });
routes.MapRouteLowerCase(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
您可以使用ActionName属性吗?
[ActionName("more_details")]
public ActionResult MoreDetails(int? page)
{
}
我认为大小写无关紧要。URL中的More_Details,more_DETAILS,mOrE_DeTaILs都将您带到同一Controller Action。