【问题标题】:C# ASP.NET MVC routing - route for all controllers with specific suffixC# ASP.NET MVC 路由 - 具有特定后缀的所有控制器的路由
【发布时间】:2015-07-17 14:00:15
【问题描述】:

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

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

【问题讨论】:

  • 你为什么要这样做..??你能说出目的吗..?

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


【解决方案1】:

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

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

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

如果需要,您可以将“小部件”重新附加到 controllerName 变量中,并将其传递给您想要的处理程序/做您想做的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多