2017-09-29 39 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" } 
);