【问题标题】:ASP.NET MVC4 Routing - access controllers and actions with identical names using different routesASP.NET MVC4 路由 - 使用不同的路由访问具有相同名称的控制器和操作
【发布时间】:2013-05-01 10:31:05
【问题描述】:

使用 ASP.NET MVC4 路由:

如果我想为网站的主要部分设置默认路由配置:

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

然后是另一个路由配置,类似下面的:

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

注意网址中的字符串“FOO/”(就在/{controller...之前

例如,我希望能够使用如下网址访问我网站的主要部分

http://dummyurl.com/bar/1

但如果我要使用,则访问具有相同名称的控制器和操作

http://dummyurl.com/**FOO**/bar/1

【问题讨论】:

    标签: asp.net-mvc-4 asp.net-mvc-routing


    【解决方案1】:
    routes.MapRoute(
        name: "FOO",
        url: "FOO/{controller}/{action}/{id}",
        defaults: new { controller = "FOO", action = "bar", id = UrlParameter.Optional }
    );
    

    这条路线会导致你可能意想不到的结果,除非你有一个名为FOO的mvc区域。该路线仅适用于http://yourdomain/foo/foo/any_method_in_foo/id

    【讨论】:

    • 区域无疑是更好的解决方案。
    【解决方案2】:

    通过routing documentation by "the Gu" 发现我只需要输入:

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

    以上:

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

    在我的Routes.config 和 blammo 中,一切顺利。我现在可以在我的项目中分离和访问例如管理员(“FOO”)部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多