mvc core 2中的用户路由

User routes in the mvc core 2

如何使用 core 2 在 mvc 中创建我的用户路由?早期,在 ASP.NET 我使用了:

context.MapRoute(
    "index",
    "index",
    defaults: new
    {
        area = "AnoterArea",
        controller = "Base",
        action = "Index"
    });

但是现在我该怎么办? 我正在尝试做类似的事情..

app.UseMvc(routes =>
{
    routes.MapAreaRoute(
        "index",
        "Index",
        "{controller}/{action}/{id?}",
        new 
        {
            controller ="Base",
            action = "Index"
        });
});

你说呢?

在 ASP MVC Core 中,您通常将这些路由添加到 Startup.cs 文件中。在 Configure() 方法中,您应该看到类似于此代码的内容:

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

从那里,您可以像这样在默认路由之上添加其他路由:

app.UseMvc(routes =>
{
         //additional route
         routes.MapRoute(
            //route parameters    
        );

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

在您的情况下,您需要添加如下内容:

routes.MapRoute(
  name: "index",
  template: "{area:exists}/{controller=Base}/{action=Index}/{id?}"
 );  

此外,您需要确保您的 Controller 位于 Areas 文件夹中,并且 Controller 操作使用 Area 名称修饰:

[Area("AnotherArea")]
public ActionResult Index()
{
    return View();
}

这是 link 一篇关于 .NET Core 中的路由的好文章:

https://exceptionnotfound.net/asp-net-core-demystified-routing-in-mvc/