I’m using MVC3 with .net membership.
I want to redirect the user to different views according to their roles.
I tried on the LogOn method of the AccountControler controller to use User.IsInRole(xxx) but it doesn’t work.
From what I’ve seen here:
Forms Authentication User.IsInRole() randomly not working in LogOn
The membership User can’t be called on that method (as it is not logged in, the cookie for logging in a user hasn’t been set yet)
I don’t think that it is relevant, but just in case, this is the LogOn method that comes by default in a MVC3 project, and the one I’ve tried to modify.
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
My question is:
What is an elegant way to redirect users according to their roles (I have just a couple of roles) on login?
I saw some recommendations that says “just query the membership database” but I don’t think that it is a proper way to do it.
Any advice?
Thanks!..
PnP
Since you linked to my question, here’s what I found out. The
User.IsInRole()gets the user name from the response. Since there is no user name in thelog onaction (without looking it up with Model.UserName) it won’t find the user in the role. If you redirect them, the user information will be added to the redirect, and it can sort the user by roles. (At least I think that’s what I found out.) Here’s what you want to do:In your account controller replace:
With:
And add: