具有可为空 ID 的 MVC 默认路由未按预期工作

MVC Default route with nullable id not working as expected

一个简单的路由方案不适合我。

我的路线注册是这样的

context.MapRoute(
                "Users_default",
                "Users/{controller}/{action}/{id}",
                new { action = "Index", id= UrlParameter.Optional });

我希望它能满足

的请求
users/profile/
users/profile/1
users/profile/2

使用以下控制器

 public class ProfileController : Controller
    {
        public ActionResult Index(int? id)
        {
            var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);
            return View(user);
        }
    }

它适用于 users/profile 但不适用于 users/profile/1 我尝试了几种不同的方法,但我知道答案一定很简单,这只是我缺乏知识,我在这里缺少什么。

这是因为您的路由解释为:
{controller: "profile", action: "1"}

您需要指出您的详细操作 url 明确,像这样:
users/profile/index/1

您可以使用Attribute routing

代码看起来像

public class ProfileController : Controller
{
    [Route("users/profile/{id}")]
    public ActionResult Index(int? id)
    {
        var user = id == null ? (UserModel)HttpContext.Session["CurrentUser"] : userManager.GetUserById((int)id);

        return View();
    }
}

并且您必须修改您的 RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // This will enable attribute routing in your project
        routes.MapMvcAttributeRoutes();

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

现在您可以将 users/profile 用于默认行为,将 users/profile/ 用于特定配置文件。

i dont want index to appear. i want to use the same method for both users/profile/1 and users/profile/

那就不要对你的 URL 采取行动了。

context.MapRoute(
    "Users_default",
    "Users/{controller}/{id}",
    new { action = "Index", id= UrlParameter.Optional });

您定义的路由不允许 index 是可选的,因为它后面跟着另一个参数(在本例中为 "id")。只有最后一个参数在除默认路由外的所有路由上都是可选的。