locked
[MVC] How to reorganize the Controller folder ? RRS feed

  • Question

  • User-1370514677 posted

    Hi everyone,

    I'm just wondering if there is a way to precise the ControllerRoute instead of the traditional :

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

    Indeed let's take this example :

    A web app has 4 controllers :

    • AdminController (Admin Role required)
    • AController.cs
    • BController.cs
    • CController.cs

    But I want to create an Admin Panel which will handle data of Controller A to C with Admin Role.

    My wish is to reorganize the Controller Folder structure like so :

    • Admin
      • AdminController.cs (Admin Role required)
      • AController.cs (Admin Role required)
      • BController.cs (Admin Role required)
      • CController.cs (Admin Role required)
    • AController.cs
    • BController.cs
    • CController.cs

    Is that possible ? If so, how to extend "asp-controller" tag scope ?

    Otherwise I can simply put the methods inside each controller with the [Authorize(Role="Admin")] but I'm just asking ;)

    Best Regards

    Thursday, February 25, 2021 4:01 PM

Answers

All replies

  • User-474980206 posted

    It does not matter what folder you put controllers in, only the controller class name matters. Maybe you want areas?

      https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-5.0

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 25, 2021 9:35 PM
  • User-1370514677 posted

    Hi @bruce,

    Thanks a lot for your answer, that's exactly what I was looking for !

    Here is my new route :

                app.UseEndpoints(endpoints =>
                {
                    // Important : you have to always follow this order to make the asp-area tag work otherwise it will take "default" as a route option
                    endpoints.MapControllerRoute(
                        name:"Admin",
                        pattern:"{area:exists}/{controller=Admin}/{action=Dashboard}/{id?}"
                    );
    
                    endpoints.MapControllerRoute(
                        name:"default",
                        pattern:"{controller=Home}/{action=Index}/{id?}"
                    );
                });

    Now I can have access to /Admin/User/Users to manage my users ;)

    Friday, February 26, 2021 10:35 AM