你表现出满足第一路径(这意味着包含段之间0和3的任何URL),和你的第三个URL中的所有3 URL(比如../User/OShai
)去的UserController
的OShai()
方法,它不存在。
您需要定义正确的顺序(第一场比赛胜)具体路线
routes.MapRoute(
name: "Register",
url: "/User/Register",
defaults: new { area = "", controller = "User", action = "Register" },
namespaces: new[] { "MvcApplication" }
);
routes.MapRoute(
name: "Login",
url: "/User/Login",
defaults: new { area = "", controller = "User", action = "Login" },
namespaces: new[] { "MvcApplication" }
);
// Match any url where the 1st segment is 'User' and the 2nd segment is not 'Register' or 'Login'
routes.MapRoute(
name: "Profile",
url: "/User/{username}",
defaults: new { area = "", controller = "User", action = "UserProfile" },
namespaces: new[] { "MvcApplication" }
);
// Default
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcApplication" }
);
凡Profile
路线将匹配
public ActionResult UserProfile(string username)
UserController
或者,你可以删除Register
和Login
路由,并为创建一个约束检查第二段的路由是否匹配“注册”或“登录”,如果匹配,则返回false,以匹配Default
路由。
public class UserNameConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
List<string> actions = new List<string>() { "register", "login" };
// Get the username from the url
var username = values["username"].ToString().ToLower();
// Check for a match
return !actions.Any(x => x.ToLower() == username);
}
}
,然后修改Profile
路线
routes.MapRoute(
name: "Profile",
url: "/User/{username}",
defaults: new { area = "", controller = "User", action = "UserProfile" },
constraints: new { username = new UserNameConstraint() }
namespaces: new[] { "MvcApplication" }
);
没有传入的参数是什么样的行动?你可以发布吗?你直接去/用户而不用任何东西后?您是否尝试使用User/MyUserName来查看它是否会触发该操作? –