View:
@using (Html.BeginForm()) {}
Controller:
[HttpPost] public ActionResult LogOn(Octopus.Monitor.Storage.Model.UserInfo model, string returnUrl) { if (ModelState.IsValid) { //自定义方法,检查登录用户是否存在 DataSet dataSet = Octopus.Monitor.Storage.Mysql.DAL.UserInfoDAL.CheckUser(model); if (dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0) { //如果存在,则根据用户ID去查询用户的角色,然后将角色类型存放于FormsAuthenticationTicket DataSet roleDataSet = Octopus.Monitor.Storage.Mysql.DAL.R_UserInfo_Role.GetUserRole(Convert.ToInt32(dataSet.Tables[0].Rows[0]["ID"])); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, model.LoginID, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), true, roleDataSet.Tables[0].Rows[0]["RoleID"].ToString() ); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.Cookies.Add(cookie); if (!String.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "提供的用户名或密码不正确。"); } } // 如果我们进行到这一步时某个地方出错,则重新显示表单 return View(model); }
Global.asax:
public override void Init(){ AuthorizeRequest += new EventHandler(MvcApplication_AuthorizeRequest);}protected void MvcApplication_AuthorizeRequest(object sender, EventArgs e){ FormsIdentity formIdentity = null; var identity = Context.User.Identity; if (identity != null) formIdentity = identity as FormsIdentity; if (formIdentity != null && formIdentity.IsAuthenticated) { var roles = formIdentity.Ticket.UserData.Split(','); Context.User = new GenericPrincipal(formIdentity, roles); }}