【问题标题】:Area routing in asp.net core 6asp.net core 6中的区域路由
【发布时间】:2022-10-24 12:52:12
【问题描述】:

我有一个.net mvc core 6 应用程序,上面有以下区域Dashboard

我在startup 中将以下配置添加到Configure

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapAreaControllerRoute(
                name: "Dashboard",
                areaName: "Dashboard",
                pattern: "D/{controller=Home}/{action=Index}/{id?}"
            );
            // other areas configurations goes here 
            endpoints.MapControllerRoute(
                name: "areas",
                pattern: "{area:exists}/{controller}/{action}/{id?}"
              );
        });
    }

上面的代码可以很好地识别每个区域路由,它将像这样工作http://localhost/d/dashboard 将重定向到Dashboard 区域问题在于如何将它与 mvc 的正常路由一起使用

   Url.Action("Index", "Dashboard", new { area = "d" })

这将生成以下链接 https://localhost/Dashboard?area=d 而不是 http://localhost/d/dashboard 即使将代码更改为这样

   Url.Action("Index", "Dashboard", new { area = "Dashboard" }) 

这将生成以下链接https://localhost/Dashboard?area=Dashboard 而不是http://localhost/d/dashboard

对这个问题有任何帮助吗?

【问题讨论】:

    标签: routes asp.net-core-mvc asp.net-core-6.0


    【解决方案1】:

    您需要将endpoints.MapDefaultControllerRoute(); 移动到最后。

    来自较早出现的路由的匹配具有更高的优先级。传统的路由是依赖于顺序的。一般来说,有区域的路线应该更早放置,因为它们比没有区域的路线更具体。

    您的路由顺序优先使用MapDefaultControllerRoute()。重定向时,默认将 Area 作为参数传递。

    更多详情可以参考this official documentation。

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 2019-03-05
      • 2018-06-30
      相关资源
      最近更新 更多