Search code examples
asp.net-mvcasp.net-coreasp.net-routing

MapAreaControllerRoute blocks MapControllerRoute


I have a problem. My MapAreaControllerRoute is blocking MapControllerRoute. That means when I open app in browser localhost:7155 it opens login as normal https://localhost:7155/login.html?ReturnUrl=%2F then after logging in it opens Admin area localhost:7155/Admin/Dashboard/Categories instead of Home controller.

Here is a part of Program.cs:

app.MapAreaControllerRoute(
    name: "areas",
    areaName: "Admin",
    pattern: "{area:exists}/{controller=Dashboard}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

I tried this: While debugging I saw that route / is a actually the admin area. Log:

--==[CALLBACK: / ]==---

Here is a part of the code:

await Request.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);

string? callbackUrl = Request.Query["ReturnUrl"];

if (!string.IsNullOrWhiteSpace(callbackUrl))
{
    Console.WriteLine($"---==[ CALLBACK: {callbackUrl} ]==---");
    return Redirect(callbackUrl);
}

Btw my controller automatically redirects to categories action


Solution

  • While debugging I saw that route / is an actually the admin area.

    In general, routes with areas should be placed earlier as they're more specific than routes without an area. And matches from a route that appears earlier have a higher priority. So, when executing the redirection, it will match the MapAreaControllerRoute first.

    That's why the program goto the "localhost:7155/Admin/Dashboard/Categories", because the "localhost:7155/" matches the first route map, then use the default controller and action as "localhost:7155/Admin/Dashboard/Index".

    So, the solution is adding a route attribute "[Route("/")]" to the Home/Index action, the program will first match the attribute.

    [Route("/")]
    public IActionResult Index()
    {
        return View();
    }