asp.net-mvcasp.net-mvc-5

Change Default landing page for users in specific Role


How to change the landing page for users that are part of some role (lets say "Admin"). To be more specific, when a user that is in role "Admin" accesses the application site ( http://localhost:1234/ ) he should be routed to "Index" action method of controller "AdminController". When all other users (that are not in role "Admin") access the site they should be routed to "Index" action method of "HomeController" controller (this is satisfied by the Default Mapped Route routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }) ).

"Admin" role users MUST NOT have access to any other controller except the "AdminController".

EDIT 1: Or is it not possible to do this using routing because the HttpContext is not formed yet, and check must be done inside some controller action method (and user redirected afterwards) ?


Solution

  • Default site is always home/index so u can set the logic under the action result.

    e.g.

     public IActionResult IndexPage(string? message)
     {
    
         if (User.IsInRole("Admin"))
         {
             return RedirectToAction("Index", "AdminController"); 
         }
         else if (User.IsInRole("Driver"))
         {
             return RedirectToAction("Index", "DriverController");
         }
         else if (User.IsInRole("Warehouse"))
         {
             return RedirectToAction("WarehouseIndex", "WarehouseController");
         }
    
         return View();
     }
    

    You may then create the controller respectively.

    To control who can access the Controller simply put the authorisation with the role as following

    [Authorize(Roles ="Admin")]
    

    That tells only users with admin role is allowed for this controller