C#ASP.NET MVC路由 - 具有特定后缀的所有控制器的路由

时间:2015-05-07 06:34:30

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

我有几个名为{WidgetName} WidgetController的小部件的控制器,例如: SampleWidgetController。我需要创建一个路由来捕获对这些控制器的所有请求,并将它们与请求的控制器名称和操作一起传递给一个公共控制器。

public class SampleWidgetController : Controller
{
    public ActionResult Content()
    {
        ...
    }
}

public class CommonController : Controller
{
    public ActionResult Content(string controllerName, string actionName)
    {
        // I want all requests to SampleWidget/Content to be passed here
        // With controllerName = "SampleWidget" and actionName = "Content"
    }
}

我可以创建一个自定义RouteConstraint来只接受那些带有'Widget'后缀的控制器,但是我在定义路由本身方面遇到了问题,该路由本身会将请求的控制器的名称和操作传递给公共控制器。

1 个答案:

答案 0 :(得分:1)

在RouteConfig RegisterRoutes方法中添加以下路线 默认值

routes.MapRoute("Widgets", "{controllerName}Widget/{actionName}",
            new { controller = "Common", action="Content"});

这会导致传入的请求与您指定的格式相匹配,例如: [baseurl]/testWidget/testaction会使用ContentcontrollerName="test"

点击您的CommonController actionName="testaction"操作

如果需要,您可以附加" Widget"回到controllerName变量并将其传递到您想要的处理程序/执行您尝试执行的操作。

相关问题