Authorize attributes not working in MVC 4

半城伤御伤魂 提交于 2019-12-24 02:17:54

问题


In my application i am using

 System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0

as my membership provider and here my Account Controller code

[HttpPost]
        public ActionResult Login(string username,string password)
        {
            var result = Membership.ValidateUser(username, password);
            if(result)
            {

                var user = Membership.GetUser(username);
                var roles = Roles.GetRolesForUser(username);
                var isDistributor = roles.Any(x => x.ToUpper() == "DISTRIBUTOR");
                if (isDistributor) return RedirectToAction("ShowCurrentDistributor", "Distributor");
            }
            else
            {
                TempData["error"] = "Invalid login attempt";
            }
            return View();
        }

And my ShowCurrentDistributor action code:

 [HttpGet]
        [Authorize(Roles = "Distributor")]
        public ActionResult ShowCurrentDistributor()
        {

            var distributor = _distributer.GetDistributerbyEmail(User.Identity.Name);
            return View(distributor);
        }

But when i call ShowCurrentDistributor method, authorization not working. it always return back to my login form even i passed authentication with valid role( Distributor). Whats wrong with my code


回答1:


You need to add the following line after successful validation:

FormsAuthentication.SetAuthCookie(username,true);

(answered in question comments by the original poster)



来源:https://stackoverflow.com/questions/21214003/authorize-attributes-not-working-in-mvc-4

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