【问题标题】:Map routes only for one controller and actions of this controller. Others routing settings leave operable仅为一个控制器和该控制器的操作映射路由。其他路由设置保持可操作
【发布时间】:2016-04-03 05:06:37
【问题描述】:

首先,我需要说我正在使用 T4MVC。我的RouteConfig 中有许多自定义路线。这是一个例子:

    routes.MapRoute("CollectionDetails", "collection/{slug}/{collectionId}", MVC.Collection.CollectionDetails());    
..............................................                     
    routes.MapRoute("Sales.Index", "sales", MVC.Sales.Index());
    routes.MapRoute("CustomPage", "custom/{slug}", MVC.CustomPage.Index());

所有这些路线都运行良好。但是我有一个控制器(AccountController),我需要在这样的方案中映射路由:ControllerName/ActionName/。 我的意思是我有Account Controller。这个控制器有这样的ActionsCreateAccount, CreateAccount(POST), ResetPassword, LogIn, etc...,我需要为它们创建这样的UrlsAccount/CreateAccountAccount/LogIn。我想知道是否可以在RouteConfig 中使用一个route 来解决?

【问题讨论】:

  • 我认为你不需要任何额外的路径来完成你的工作,你可以直接通过 html helper html.actionlink("create",account,new{id=model.id} ) 它会是你想要的那种 url,如果你想传递任何 id,id 是可选的,那么你可以使用,否则只有两个参数就足够了。

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


【解决方案1】:

如果您想锁定到特定控制器的路由(在您的情况下,只是到帐户控制器),那么您可以使用 T4MVC 执行此操作:

来自 T4MVC 文档:2.2.5 routes.MapRoute

routes.MapRoute(
     "Account",
     "Account/{action}/{id}",
      MVC.Account.Index(null));

否则你也可以用

达到同样的效果

来自文档2.3. Use constants to refer to area, controller, action and parameter names

routes.MapRoute(
     name: "Account",
     url: "Account/{action}/{id}",
     defaults: new { controller = MVC.Account.Name, action = MVC.Account.ActionNames.Index, id = UrlParameter.Optional }
);

或者回到默认的做法

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

这应该满足您的要求。

【讨论】:

    【解决方案2】:

    使用默认 MVC 路由:

    routes.MapRoute(
                    "Default",                                              // Route name
                    "{controller}/{action}/{id}",                           // URL with parameters
                    new { controller = MVC.Home.Name, action = MVC.Home.ActionNames.Index, id = "" }  // Parameter defaults
                );
    

    你应该能够实现你想要的..

    只要在列表底部定义了它,您的海关路线就会在它之前触发并且它们将继续工作。当涉及到帐户 URL 时,您的自定义路由将不匹配,它们将使用默认路由到帐户控制器和 URL 中指定的操作。

    更多关于MVC路由http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/asp-net-mvc-routing-overview-cs

    【讨论】:

    • 更新了将 T4MVC 用于默认控制器和操作的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多