对一个控制器有不同动作的路由控制器

对一个控制器有不同动作的路由控制器

问题描述:

为了讨论起见,我们假设我有两个控制器:Alpha和Beta。而且,假设我想将它们映射到相同的动作,但在一个或另一个控制器上:/ Alpha/DoThis &/Beta/DoThis会发送到/ Alpha/DoThis或甚至是/ Omega/DoThis。如何做到这一点?对一个控制器有不同动作的路由控制器

~/App_Start/RouteConfig.cs将是我的猜测(或Application_Start,如果你没有一个):

// just in case you need the alias 
//var routes = RouteCollection.Routes; 

routes.MapRoute(
    name: "RedirectSomeRoutes", 
    url: "{originalController}/DoThis", 
    defaults: new { 
     controller = "Alpha", // Use this controller 
     action = "DoThis", // And use this action 
    }, 
    // Setup constraints so it only runs against the supplied 
    // matching controllers (e.g. Alpha, Beta and Omega) 
    constraints: new { 
     originalController = "^Alpha|Beta|Omega$" 
    } 
); 

注意MVC与RouteTable中的第一场比赛中运行,所以你要首先列出最具体的路线,和最通用的(通常是{controller}/{action}/{id})。

或者,您可以使用重写(在您的web.config之内),这将为响应代码等提供更多的权力(例如403重定向)。

+0

如果我想匹配任何控制器?我想我需要修改originalController与任何正则表达式?即“*”? – EDanaII 2014-10-06 21:00:54

+0

只需从'MapRoute'中删除'constraint'参数(默认约束类似于'。*')。 – 2014-10-07 12:50:42