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...

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

2 Answers2

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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? – Howiecamp Aug 25 '14 at 05:36
  • 1
    @Howiecamp 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). – Caleb Vear Nov 26 '14 at 03:42
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

Mark
  • 379
  • 3
  • 11