ASP.NET控制器的核心路由和索引操作

ASP.NET Core route of a controller and the index action

我正在尝试设置我的控制器的路由,同时还能够在不键入 Index 的情况下导航索引,这是我尝试过的:

我的路由配置

app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

尝试#1

// My controller
[Route("panel/admin")]
public class MyController...

// My index action
public IActionResult Index()...

问题:这不起作用,所有操作都可以在 panel/admin 访问,所以我收到一条错误消息 Multiple actions matched
即使将我的索引操作的路由设置为 Route(""),也不会改变任何内容。

试试#2

// My controller
[Route("panel/admin/[action]")]
public class MyController...

// My index action
[Route("")]
public IActionResult Index()...

这里,索引路由没有变化,保持panel/admin/Index

我想要的

我希望在导航至 panel/admin 时能够访问我的索引操作,并且我还希望我的其他操作仅使用它们的方法名称,例如 panel/admin/UsersList.

完整控制器

[Route("panel/admin/[action]")]
public class MyController
{

    [Route("")]
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult UsersList()
    {
        var users = _db.Users.ToList();
        return View(users);
    }

    // Other actions like UsersList

}

谢谢。

引用Routing to controller actions in ASP.NET Core

对于属性路由,您必须非常具体地指定所需路由以避免路由冲突。这也意味着您将必须指定所有路线。不同于基于约定的路由。

选项 #1

[Route("panel/admin")]
public class MyController {

    [HttpGet]
    [Route("")] //GET panel/admin
    [Route("[action]")]  //GET panel/admin/index
    public IActionResult Index() {
        return View();
    }

    [HttpGet]
    [Route("[action]")] //GET panel/admin/UsersList
    public IActionResult UsersList() {
        var users = _db.Users.ToList();
        return View(users);
    }

    // Other actions like UsersList
}

选项 #2

[Route("panel/admin/[action]")]
public class MyController {

    [HttpGet] //GET panel/admin/index
    [Route("~/panel/admin")] //GET panel/admin        
    public IActionResult Index() {
        return View();
    }

    [HttpGet] //GET panel/admin/UsersList
    public IActionResult UsersList() {
        var users = _db.Users.ToList();
        return View(users);
    }

    // Other actions like UsersList
}

[Route("~/panel/admin")] 中的波浪号 (~) 覆盖控制器上的路由前缀。

Tip

While using multiple routes on actions can seem powerful, it's better to keep your application's URL space simple and well-defined. Use multiple routes on actions only where needed, for example to support existing clients.