你表現出滿足第一路徑(這意味着包含段之間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來查看它是否會觸發該操作? –