用户路由在mvc核心2中

时间:2017-11-12 18:26:21

标签: c# asp.net-core-mvc asp.net-core-2.0

如何在核心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"
        });
});

你怎么说?

1 个答案:

答案 0 :(得分:0)

在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("AnotherArea")]
public ActionResult Index()
{
    return View();
}

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

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