Reputation: 73
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
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 View
s:
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 View
s, but such use-cases happen and that's how you can easily implement them.
Upvotes: 0
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