RegisteredUser usr = db.RegisteredUsers.FirstOrDefault(a => a.LoginName == login
这是一个登陆验证。
问题:
RegisteredUser usr = db.RegisteredUsers.FirstOrDefault(a => a.LoginName == loginName && a.Passwd == encPwd); ////有相应RegisteredUsers数据库表
lambda返回的应该是一个IEnumerable的数据吧? RegisteredUser 类型只有1个属性和一个索引器, 才看MVC、linq的,有些混,表达不清
AccountController.cs
[HttpPost] public ActionResult Login(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { RegisteredUser usr = RegisteredUserBLL.AuthenticateUser(model.UserName, model.Password); if (usr != null) { FormsAuthentication.SetAuthCookie(model.UserName + "|" + usr.RealName + "|" + usr.UserType, model.RememberMe); //身份验证票,并添加到响应的cookie集合 或者url中 if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) return Redirect(returnUrl); //转到页面 return RedirectToAction("Index", "Home"); //转到页面 } ModelState.AddModelError("", "登录账号或密码不正确"); //数据库没有查询到 } return View(model); }
public class LogOnModel { [Required] [Display(Name = "账号")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [Display(Name = "密码")] public string Password { get; set; } [Display(Name = "记住登录信息")] public bool RememberMe { get; set; } }
public static class RegisteredUserBLL public static RegisteredUser AuthenticateUser(string loginName, string passwd) { using(var db=new VODDataContext()) { db.ObjectTrackingEnabled = false; string encPwd = CommonUtils.EncryptPassword(passwd); //返回一个加密的字符串 RegisteredUser usr = db.RegisteredUsers.FirstOrDefault(a => a.LoginName == loginName && a.Passwd == encPwd); ////有相应RegisteredUsers数据库表 if (usr != null) return usr; return null; } }
public partial class RegisteredUser:IDataErrorInfo { public string this[string propName] { get { if (propName == "UserName" && string.IsNullOrEmpty(LoginName)) return "用户登录名不能为空"; return string.Empty; } } public string Error { get { return string.Empty; } } }