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

C# ASP.NET MVC routing - route for all controllers with specific suffix

我有几个名为 {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' 后缀的控制器,但我在定义路由本身时遇到问题,该路由会将请求的控制器的名称和操作传递给公共控制器。

在您的 RouteConfig RegisterRoutes 方法中添加以下路由 默认值之前:

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

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

命中您的 CommonController Content 操作

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