P.Milan
P.Milan

Reputation: 73

ASP.NET MVC - Multiple default index pages depending on role

Is it possible to do role-based redirect through routes? My aim is to redirect the user to homepage based on his role, without using RedirectToAction in login action (POST) to enhance responsiveness of the site.

I want something like this.

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

        if (User.IsInRole("Admin"))
        {
            routes.MapRoute(
                "Admin", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "User", action = "List", id = UrlParameter.Optional } // Parameter defaults
            );
        }
        else
        {
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
    }

Upvotes: 0

Views: 1791

Answers (2)

Dmitry Karpenko
Dmitry Karpenko

Reputation: 592

If you want the route for both of the cases to be the same, but the pages are to have different content, you may also return different Views:

public ActionResult GetStartPage()
{
   // ...

   if (User.IsInRole("Admin"))
   {
     return View("~/Views/Home/List.cshtml", viewModel);
   }
   else
   {
     return View("~/Views/Home/Index.cshtml", viewModel);
   }
}

It's not the best way to organize your Views, but such use-cases happen and that's how you can easily implement them.

Upvotes: 0

Brian Mains
Brian Mains

Reputation: 50728

Routes are setup on application startup, so the routes are established before the user is authenticated and such. What you can do is use a generic action method:

public ActionResult Go()
{
   if (User.IsInRole("Admin")) {
     return RedirectToAction("List", "User");
   }
   else {
     return RedirectToAction("Index", "Home");
   }
}

Navigate all users to this Go action method, and it will redirect them to the appropriate place.

Upvotes: 1

Related Questions