Mvc area routing?
Asked Answered
S

2

18

Area folders look like :

Areas 
    Admin
        Controllers
            UserController
            BranchController
            AdminHomeController

Project directories look like :

Controller
    UserController
        GetAllUsers

area route registration

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional },
        new { controller = "Branch|AdminHome|User" }
    );
}

project route registration

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new string[] { "MyApp.Areas.Admin.Controllers" });
}

When I route like this: http://mydomain.com/User/GetAllUsers I get resource not found error (404). I get this error after adding UserController to Area.

How can I fix this error?

Thanks...

Senghor answered 25/3, 2013 at 13:32 Comment(0)
I
33

You've messed up your controller namespaces.

Your main route definition should be:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new string[] { "MyApp.Controllers" }
);

And your Admin area route registration should be:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional },
        new { controller = "Branch|AdminHome|User" },
        new[] { "MyApp.Areas.Admin.Controllers" }
    );
}

Notice how the correct namespaces should be used.

Inwardness answered 25/3, 2013 at 13:43 Comment(2)
I've been confused by the namespaces that correspond to the areas. In this example the namespace MyApp.Areas.Admin.Controllers matches the folder hierarchy however namespace definition is arbitrary right? Meaning the programmer could assign any namespace to the controller class that they wanted - I thought. Or is there some asp.net mvc convention that requires he namespace to match the folder hierarchy?Alyssaalyssum
@Alyssaalyssum the default behaviour of Visual Studio is to match the namespace to the folder hierarchy and that is what you will typically see in all .net projects (not just MVC projects).Bandsman
P
4

An up to date solution for ASP.NET Core MVC.

[Area("Products")]
public class HomeController : Controller

Source: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas

Popularize answered 11/3, 2018 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.