【问题标题】:User routes in the mvc core 2mvc 核心 2 中的用户路由
【发布时间】:2018-04-25 10:16:18
【问题描述】:

如何使用 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"
        });
});

你说什么?

【问题讨论】:

  • 您应该正确地格式化您的代码,以便他人阅读。
  • @Heri 你能说更多吗?

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


【解决方案1】:

在 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/

【讨论】:

  • 谢谢)而且.. 如果我需要添加另一个区域怎么办?我在哪里可以写这个?
  • 添加了添加新区域的示例。
  • 看起来很简单)再次感谢)
  • 没问题。如果您想了解所有详细信息,这里有一个很好的 post 解释了在 ASP MVC Core 中使用区域的完整纲要。
猜你喜欢
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
  • 2017-03-02
  • 2018-07-07
相关资源
最近更新 更多