[英]C# ASP.NET MVC routing - route for all controllers with specific suffix
I have several controllers for widgets named {WidgetName}WidgetController, eg SampleWidgetController. 我有几个用于名为{WidgetName} WidgetController的小部件的控制器,例如SampleWidgetController。 I need to create a route which catches all requests to such controllers and passes them to one common controller together with requested controller's name and action.
我需要创建一条路由,以捕获所有对此类控制器的请求,并将它们与所请求控制器的名称和操作一起传递给一个通用控制器。
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"
}
}
I can create a custom RouteConstraint to accept only those controllers that have 'Widget' suffix, but I have a problem with defining the route itself which will pass the requested controller's name and action to the common controller. 我可以创建一个自定义RouteConstraint来仅接受带有“ Widget”后缀的那些控制器,但是我在定义路由本身时遇到了问题,该路由本身会将请求的控制器的名称和操作传递给公共控制器。
In your RouteConfig RegisterRoutes
method add the following route before the default: 在您的RouteConfig
RegisterRoutes
方法中,在默认值之前添加以下路由:
routes.MapRoute("Widgets", "{controllerName}Widget/{actionName}",
new { controller = "Common", action="Content"});
This will cause incoming requests matching the format you've specified, eg [baseurl]/testWidget/testaction
would hit your CommonController Content
Action with a controllerName="test"
and actionName="testaction"
这将导致与您指定的格式匹配的传入请求,例如
[baseurl]/testWidget/testaction
将使用controllerName="test"
和actionName="testaction"
命中您的CommonController Content
Action
If needed you can then append the "Widget" back onto the controllerName
variable and pass it into your desired handler / do what you're trying to do. 如果需要,您可以将“窗口小部件”附加回
controllerName
变量,然后将其传递到所需的处理程序中/执行您要执行的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.