如何防止多个ASP.NET MVC路由映射

Hal*_*yon 6 html c# asp.net asp.net-mvc asp.net-mvc-3

我有一个ASP.NET MVC路由问题.首先,让我解释一下我的区域设置.这很简单.

Areas
|
+--Foo
   |
   +--Controllers
      |
      +--BarController.cs
Run Code Online (Sandbox Code Playgroud)

我的区域中有一个名为"Foo"的文件夹和名为"BarController.cs"的控制器.Bar控制器有几个名为"DoStuff1()","DoStuff2()"等的方法.

我的网站使用以下网址:

/foo/bar/15
/foo/bar/dostuff1
/foo/bar/dostuff2
Run Code Online (Sandbox Code Playgroud)

第一个URL需要一个id,并使用Bar控制器中的默认Index()方法使用视图和模型填充网页.

在第二个和第三个URL中,我将它们用于jQuery ajax调用.

这是我所在区域注册的代码

context.MapRoute(null, "Foo/Bar/DoStuff1", new
{
    action = "DoStuff1",
    controller = "Bar"
});

context.MapRoute(null, "Foo/Bar/DoStuff2", new
{
    action = "DoStuff2",
    controller = "Bar"
});

context.MapRoute(null, "Foo/Bar/{id}", new
{
    action = "Index",
    controller = "Bar"
});
Run Code Online (Sandbox Code Playgroud)

我的问题是,对于我创建的每个新控制器方法,我必须在区域registrion文件中添加另一个路由映射.例如,如果我添加方法DoStuff3(),我需要将其添加到区域注册:

context.MapRoute(null, "Foo/Bar/DoStuff3", new
{
    action = "DoStuff3",
    controller = "Bar"
});
Run Code Online (Sandbox Code Playgroud)

如何创建通用路由映射来处理上面提到的URL,这些URL不需要为新控制器方法添加区域注册文件?

yoo*_*er8 3

您可以拉出控制器操作。

像这样写 URL:

"Foo/Bar/{action}"
Run Code Online (Sandbox Code Playgroud)

此外,您也可以拔出控制器,然后写入

"Foo/{controller}/{action}"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,action = "Index"如果未提供操作参数,则提供默认值“Index”。

在这种情况下,您需要消除"Foo/Bar/{action}"和之间的歧义"Foo/Bar/{id}"。由于匹配是按顺序完成的,因此您需要将路线放在第一位,并向参数id添加数字约束id。这允许有效的数字 ID 与其匹配,并且操作名称可以跳到下一个路由。您的两条路线将如下所示:

context.MapRoute(null, "Foo/Bar/{id}", new
{
    action = "Index",
    controller = "Bar"
},
new { id = @"\d+" });

context.MapRoute(null, "Foo/Bar/{action}", new
{
    action = "Index", //optional default parameter, makes the route fall back to Index if no action is provided
    controller = "Bar"
});
Run Code Online (Sandbox Code Playgroud)