【问题标题】:Routing on same URL in MVC4在 MVC4 中的相同 URL 上路由
【发布时间】:2014-09-11 01:36:39
【问题描述】:

我正在为区域编写路线,但我在同一个 URL 上遇到了问题。这是我的网络结构:

Project Authentication:
AccountController 
|__SignIn

Project Account: 
AccountController 
|__ChangePassword

我写路线:

AccountAreaRegistration 中的第一条路由:

context.MapRoute(
    "Account_Default",
    "Account/{action}/{id}",
    new
    {
        controller = "Account",
        id = UrlParameter.Optional
    },
    new[] { "MyProject.Account.Controllers" });

AuthenticationAreaRegistration 中的第二条路由:

context.MapRoute(
    "Authentication_Account",
    "Account/SignIn",
    new
    {
        controller = "Account",
        action = "SignIn",
        id = UrlParameter.Optional
    },
    new[] { "MyProject.Authentication.Controllers" });

第一个路由的优先级高于第二个路由,因为 AccountAreaRegistration 在 AuthenticationAreaRegistration 之前调用。

当我打开 URL:~/Account/SignIn -> 我收到错误资源未找到,因为此 URL 与第一个路由匹配。如何解决我的问题。谢谢。

【问题讨论】:

    标签: c# .net asp.net-mvc routing


    【解决方案1】:

    如果您愿意修改路线模板,您可以这样做:

       public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "Authentication_Account",
                "Authentication/SignIn",
                new
                { 
                    controller = "Account",
                    action = "SignIn",
                    id = UrlParameter.Optional
                },
                new[] { "MyApp.Areas.Authentication.Controllers" });
        }
    

    它只修改你的“Authentication_Account”模板,这会让你 使用 ~/Authentication/SignIn 和 ~/Account/ChangePassword 访问您的操作 - 只需使 url 唯一。

    如果这还不够好,您可以以不同的顺序调用路由注册函数,以便首先注册更具体的路由 - 在您的情况下是“Authentication_Account”路由。您将需要手动调用它们,而不是在 Global.asax 中使用 RegisterAllAreas

    【讨论】:

      【解决方案2】:

      您想为不同的区域使用相同的前缀 url,如 Account/.../..? 我认为这不是最佳做法,但如果你真的想要它,你可以剪切第二条路线并将其粘贴在第一条路线之前。并让您的 AuthenticationAreaRegistration MapRoute 为空。

      所以您的 AccountAreaRegistration 会是这样的:

      context.MapRoute(
      "Authentication_Account",
      "Account/SignIn",
      new
      {
          controller = "Account",
          action = "SignIn",
          id = UrlParameter.Optional
      },
      new[] { "MyProject.Authentication.Controllers" });
      context.MapRoute(
      "Account_Default",
      "Account/{action}/{id}",
      new
      {
          controller = "Account",
          id = UrlParameter.Optional
      },
      new[] { "MyProject.Account.Controllers" });
      

      【讨论】:

        猜你喜欢
        • 2014-04-20
        • 2016-06-20
        • 2015-04-23
        • 2020-07-12
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        相关资源
        最近更新 更多