2017-09-29 42 views
2

我有一個UserController採取以下操作:RegisterLoginUserProfileMVC 5路由網址不工作

,以便爲這些行爲,我想要的網址的是:

Register - /用戶/註冊

Login - /用戶/註冊

UserProfile - /用戶/ {用戶名}(只有在發現 未發現任何操作時,此路由纔會控制)

所以這是我RouteConfig.cs看起來像:

// Default: 
routes.MapRoute(
    name: "Default", 
    url: "{controller}/{action}/{id}", 
    defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }, 
    namespaces: new[] { "MvcApplication" } 
); 

// User Profile - Default: 
routes.MapRoute(
    name: "UserProfileDefault", 
    url: "User/{username}", 
    defaults: new { area = "", controller = "User", action = "UserProfile" }, 
    namespaces: new[] { "MvcApplication" } 
); 

我需要的,只有當有一個在UserController沒有采取的措施控制UserProfile路線將採取控制。

不幸的是,我的代碼不工作,我得到一個404導航 到UserProfile路線,但所有其他UserController行動正在工作。

我也搬到了UserProfile路線到頂端,仍然沒有工作,我試了一切,似乎沒有任何工作。

+0

沒有傳入的參數是什麼樣的行動?你可以發佈嗎?你直接去/用戶而不用任何東西后?您是否嘗試使用User/MyUserName來查看它是否會觸發該操作? –

回答

4

你表現出滿足第一路徑(這意味着包含段之間0和3的任何URL),和你的第三個URL中的所有3 URL(比如../User/OShai)去的UserControllerOShai()方法,它不存在。

您需要定義正確的順序(第一場比賽勝)具體路線

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

或者,你可以刪除RegisterLogin路由,併爲創建一個約束檢查第二段的路由是否匹配「註冊」或「登錄」,如果匹配,則返回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" } 
);