就其本身而言,您的路由将不起作用,因为如果url
.../Product意味着您想要导航至的
Index()方法
ProductController,则它将与您的第一个路由匹配(并假设“
Product”为
username。您需要向您的路线添加路由约束
true如果
username有效,
false则返回定义,否则无效(在这种情况下,它将尝试以下路线查找匹配项)。
假设您有
UserController以下方法
// match http://..../Bryanpublic ActionResult Index(string username){ // displays the home page for a user}// match http://..../Bryan/Photospublic ActionResult Photos(string username){ // displays a users photos}然后您需要定义路线
public class RouteConfig{ public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "User", url: "{username}", defaults: new { controller = "User", action = "Index" }, constraints: new { username = new UserNameConstraint() } ); routes.MapRoute( name: "UserPhotos", url: "{username}/Photos", defaults: new { controller = "User", action = "Photos" }, constraints: new { username = new UserNameConstraint() } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional } ); } public class UserNameConstraint : IRouteConstraint { public bool Match(HttpContextbase httpContext, Route route, string parameterName, RoutevalueDictionary values, RouteDirection routeDirection) { List<string> users = new List<string>() { "Bryan", "Stephen" }; // Get the username from the url var username = values["username"].ToString().ToLower(); // Check for a match (assumes case insensitive) return users.Any(x => x.ToLower() == username); } }}如果url为
.../Bryan,则它将与
User路由匹配,并且您将在中执行
Index()方法
UserController(并且的值
username将为
"Bryan")
如果url为
.../Stephen/Photos,则它将与
UserPhotos路由匹配,并且您将在中执行
Photos()方法
UserController(并且的值
username将为
"Stephen")
如果url为
.../Product/Details/4,则对于前两个路由定义,路由约束将返回false,并且您将执行的
Details()方法
ProductController
如果url为
.../Peteror
.../Peter/Photos且没有用户使用,
username = "Peter"则它将返回
404Not Found
请注意,上面的示例代码对用户进行了硬编码,但实际上,您将调用返回包含有效用户名的集合的服务。为了避免打入数据库的每个请求,您应该考虑使用
MemoryCache来缓存集合。该代码将首先检查它是否存在,如果不存在,则检查集合中是否包含
username。如果添加了新用户,您还需要确保缓存无效。



