关于Core3的多Area路由问题

2020-03-19 10:09发布

问题:

https://www.cnblogs.com/lonelyxmas/p/10934388.html
我参考这个写了个包含Area的asp.net core 程序(Core版本3.1.1/3.1.2)
Startup的核心代码如下

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthorization();

        app.Use((context, next) =>
        {
            var route = context.GetRouteData();
            var endpoint = context.GetEndpoint();//拿到终结点                
            var routeData = context.Request.RouteValues;//拿到路由数据
            Console.WriteLine("=======");

            Console.WriteLine("route:" + route.ToJson());
            Console.WriteLine("endpoint:" + endpoint?.DisplayName);
            Console.WriteLine("routeData:" + routeData.ToJson());                             //做些牛B的事
            return next();
        });
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapAreaControllerRoute(
                name: "areas",
                areaName: "areas",
                pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}",
                defaults: new { Area = "admin", Controller = "Home", Action = "Index" });
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Area下的HomeController代码如下

[Area("Admin")]
[Route("Admin/[controller]/[action]")]
public class HomeController : Controller
{
    public IActionResult Index(string id)
    {
        return Json($"Index Id:{id}");
    }
}

但是很奇怪的是当我访问完整地址(比如 http://localhost:5000/admin/home/index)
一切正常
当我不带Controller和Action访问网址访问(比如http://localhost:5000/admin 或者http://localhost:5000/admin/home)
会报404,endpoint为空
当我用直接用参数访问网址(比如 http://localhost:5000/admin/home/index?id=1000)
一切正常
当我用路由模式带参数访问网址(比如 http://localhost:5000/admin/home/index/1000)
会报404,endpoint为空
代码运行结果如下图:

我想请教一下这个是我哪里搞错了,或者有什么方法可以做到以前Mvc4那样的路由效果

备注:我特意新建了一个Web程序,只添加以上代码也会出现一样的问题。

回答1:

去掉 [Route("Admin/[controller]/[action]")] 试试