Asp.net mvc MVC 5路由Url不工作

Asp.net mvc MVC 5路由Url不工作,asp.net-mvc,routes,asp.net-mvc-5,Asp.net Mvc,Routes,Asp.net Mvc 5,我有一个具有以下操作的UserController:注册,登录,和用户配置文件 对于这些操作,我希望URL为: 寄存器-/User/Register 登录-/User/Login UserProfile-/User/{username}(只有当 (未找到任何操作) 这就是我的RouteConfig.cs的样子: // Default: routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}",

我有一个具有以下操作的
UserController
注册
登录
,和
用户配置文件

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

寄存器
-/User/Register

登录
-/User/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
路由移到了顶部,但仍然不起作用,我尝试了所有方法,但似乎都不起作用。

您显示的所有3个url都与第一个路由匹配(这意味着任何包含0到3个段的url),而您的第三个url(比如
。/User/OShai
)则是
OShai()
用户控制器的方法,该方法不存在

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

其中,
配置文件
路线将匹配

public ActionResult UserProfile(string username)
UserController

或者,您可以删除
注册
登录
路由,并为
配置文件
路由创建一个约束,以检查第二段是否与“注册”或“登录”匹配,如果是,则返回false,使其与
默认
路由匹配

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);
    }
}

传入参数在操作中是什么样子的?你能把它寄出去吗?然后你直接去/User,不使用后面的任何东西?您是否尝试过User/MyUserName以查看它是否会影响操作?
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);
    }
}
routes.MapRoute(
    name: "Profile",
    url: "/User/{username}",
    defaults: new { area = "", controller = "User", action = "UserProfile" },
    constraints: new { username = new UserNameConstraint() }
    namespaces: new[] { "MvcApplication" }
);