MVC 5路由URL不起作用

时间:2017-09-29 18:43:58

标签: asp.net-mvc routes asp.net-mvc-5

我有一个UserController,其中包含以下操作:RegisterLoginUserProfile

对于这些操作,我希望URL为:

  

Register - /用户/注册

     

Login - /用户/登录

     

UserProfile - / User / {username}(此路由仅在以下情况下才会获得控制权   没有找到任何行动)

这就是我的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" }
);

我需要UserProfile的路线只有在UserController无法控制的情况下才能获得控制权。

不幸的是,我的代码无效,我获得了404导航功能  到UserProfile路由,但所有其他UserController操作都正常。

我还将UserProfile路线移到了顶部但仍然无法正常工作,我尝试了一切,似乎没什么用。

1 个答案:

答案 0 :(得分:4)

您显示的所有3个网址都匹配第一条路线(这意味着任何包含0到3个网段的网址),而您的第3个网址(比如../User/OShai)则采用OShai()方法UserController 1}}不存在。

您需要以正确的顺序定义特定路线(第一场比赛获胜)

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路由,并为Profile路由创建约束,以检查第2段匹配“注册”或“登录”,以及如果是这样,则返回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" }
);