[HttpPost]
public ActionResult LogOn(User model, string returnUrl)
{
if (ModelState.IsValid)
{
if (model.Logon())
{
string str = model.UserRole;
// 两种登录代码都可以,如果要涉及到角色,必须要在在Global.asax.cs文件中需要添加AuthorizeRequest事件处理代码
// 1.这种适用于一般的情况,如果在用这种登录代码,则在Global.asax.cs的AuthorizeRequest必须要为用户去数据库中查询角色,然后添加进去
//FormsAuthentication.SetAuthCookie(model.UserName, true);
// 2. 这种适用于带角色的登录,角色可以放在UserData里面,在AuthorizeRequest事件中可以直接拿出来使用
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
model.UserName,
DateTime.Now,
DateTime.Now.Add(FormsAuthentication.Timeout),
true,//model.RememberMe,
model.UserRole
);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
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);
}
public ActionResult LogOff()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
在Global.asax.cs中:
public MvcApplication()
{
this.AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);
}
void MvcApplication_AuthorizeRequest(object sender, EventArgs e)
{
var id = Context.User.Identity as FormsIdentity;
if (id != null && id.IsAuthenticated)
{
var roles = id.Ticket.UserData.Split(',');
Context.User = new GenericPrincipal(id, roles);
}
}