繁体   English   中英

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 Action

如果需要,您可以将“窗口小部件”附加回controllerName变量,然后将其传递到所需的处理程序中/执行您要执行的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM