ASP.Net MVC 4 Getting Roles during login to redirect to appropriate page

a 夏天 提交于 2020-01-05 07:30:09

问题


I am trying to redirect the user to the appropriate page on login. So I check to see if they are in a role and then redirect based on membership. However, Roles.IsUserInRole() doesn't seem to work. Plus when I use Roles.GetRolesForUser("username") I get "System.String[]". I am using the default simplemembership in mvc4. I can see the users created in the database and are linked to the appropriate roles. Also, when I use the [Authorize Roles..] that works fine. Here is my login(Pretty much the default login with my Role Check and redirect added.

public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {   //Get list of roles to print
                Session["FName"] = Roles.GetRolesForUser(model.UserName);
                if(Roles.IsUserInRole(model.UserName,"User")){
                    return RedirectToAction("Index","UserLanding");
                    Session["FName"] = "User in User group";
                }
                return RedirectToLocal(returnUrl);
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

I would expect when a user logs in in the "user" group they get redirected to the UserLanding Congroller Index page. However, they always get redirected to the Home page.


回答1:


I guess you can't access Roles.IsUserInRole or GetRolesForUser until after a redirect, hence the empty values. I found this here under role based authorization. If somebody has a way to access the roles directly in the DB without going through Role I could use that. But in the meantime I will just implement the additional redirect as suggested in the article.




回答2:


you can validate user manually so that you can access membership class which recognize particular user, and then you can access all user related data like roles, etc.

here is the code that you have to add to validate user manually before accessing role,

 Membership.ValidateUser("Username", "PASSWORD");
 FormsAuthentication.SetAuthCookie(usermaster.Useremail, true);

hope this my help you. raj



来源:https://stackoverflow.com/questions/12715625/asp-net-mvc-4-getting-roles-during-login-to-redirect-to-appropriate-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!