1

家庭控制器

 [Authorize(Roles = "Member")]
public ActionResult Contact()
{
    return View();
}

全球.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        //Construst the GeneralPrincipal and FormsIdentity objects
        var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (null == authCookie)
        {
            //no authentication cokie present
            return;
        }
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        if (null == authTicket)
        {
            //could not decrypt cookie
            return;
        }
        //get the role
        var role = authTicket.UserData.Split(new[] { ',' });
        var id = new FormsIdentity(authTicket);
        Context.User = new GenericPrincipal(id, role);
    }

帐户控制器

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && _userbll.ValidateUser(model.UserName, model.Password))
        {
            var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, model.RememberMe ? DateTime.Now.AddDays(14) : DateTime.Now.AddMinutes(30), model.RememberMe, "Member"); 
            var hashTicket = FormsAuthentication.Encrypt(ticket);
            var userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            Response.Cookies.Add(userCookie);
            return RedirectToLocal(returnUrl);
        }
        ModelState.AddModelError("", "error");
        return View(model);
    }

FormsAuthenticationTicket userData = "会员"

最后,使用内置的 Membership Role 机制

结果还是使用了 Membership Role 组合的机制</p>

mvc3可以读取userData

4

0 回答 0