【问题标题】:ASP.NET MVC4 Routing - Multiple routes to the same locationASP.NET MVC4 路由 - 到同一位置的多个路由
【发布时间】:2013-04-28 16:34:51
【问题描述】:

我正在设置单页应用程序 (SPA) 并希望设置,目前有两条路线。例如:

  • 路由 1:http://localhost - 这是需要身份验证的默认路由(管理区域)
  • Route 2:http://localhost/<client>/<clients project name>/ - 这不需要身份验证(仅供查看)

在管理区域,他们设置了<client><clients project name>,因此我知道我需要在 MVC4 Routes 中设置此配置,但我不清楚我将如何处理。

另一个警告是,如果<clients project name> 没有输入到 URL 中,它将显示该客户端的搜索页面。

【问题讨论】:

    标签: asp.net-mvc c#-4.0 asp.net-mvc-4 asp.net-mvc-routing single-page-application


    【解决方案1】:

    MVC 中路由的一大优点是能够将任何内容路由到任何地方,无论 url 是否与控制器和操作方法的命名匹配。 RouteConfig 允许我们注册特定的路由来满足这一点。让我向您展示如何实现这一目标。

    路线 1:

    这由路由配置中的默认路由处理。

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

    点击http://localhost 会将您带到Home 控制器和Index 操作方法。

    路线 2:

    我们可以设置一条路线来满足http://localhost/<client>http://localhost/<client>/<clients project name> 的需求

    routes.MapRoute(
        "Client", 
        "{client}/{title}", 
        new { controller = "Home", 
              action = "Client", 
              title = UrlParameter.Optional });
    

    点击http://localhost/baconhttp://localhost/bacon/smokey 将带您进入Home 控制器和Client 操作方法。注意title 是一个可选参数,这是我们如何让两个 url 使用相同的路由。

    为了在控制器端上运行,我们的操作方法Client 需要如下所示。

    public ActionResult Client(string client, string title = null)
    {
        if(title != null)
        {
           // Do something here.
        }
    }
    

    【讨论】:

    • 多么棒的解释。谢谢你!我相信这会让我在未来遇到更多问题。
    • 这也适用于 Web API 路由吗?哪里不使用 MapRoute 而只是使用 MapHttpRoute?
    • 是的,这也可以与 MapHttpRoute 一起使用
    • 好的,我已经实现了这个,但现在它与我的登录管理冲突。它调用/Account/Logoff,格式和上面一样。有没有办法可以将所有帐户请求传递到它的特定区域?
    • 您只需要为 Account 控制器创建一个特定的路由。例如。 routes.MapRoute("Account", "Account/{action}", new { controller = "Account" });
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    相关资源
    最近更新 更多