书上的验证时在配置文件中直接声明用户名和密码,想改成从数据验证账号和密码,搞了一下午都没高出来,不断的调试,发现
var table = userInfo.Tables.FirstOrDefault(x => x.Name == user.Name);
这句代码有问题,一直时Null,各种百度无法解决,就把它转成userInfo.Tables.AsQueryable();了。完美解决了
控制器代码
public class AccountController : Controller { IAuthProvider authProvider; ITaableInfo userInfo; public AccountController(IAuthProvider autho,ITaableInfo info) { authProvider = autho; //获得用户数据 userInfo = info; //EFDbcontext context = new EFDbcontext(); //context.SaveChanges(); } public ViewResult Login2() { return View(); } //[HttpPost] //public ActionResult Login(LoginViewModel model, string returnUrl) //{ // if (ModelState.IsValid) // { // if (authProvider.Authenticate(model.Name, model.PassWord)) // { // return Redirect(returnUrl ?? Url.Action("Index", "Admin")); // } // else // { // ModelState.AddModelError("", "Incorrect userName,passWord"); // return View(); // } // } // else // { // return View(); // } //} [HttpPost] public ActionResult Login2(Admin user, string returnUrl) { //foreach (var B in userInfo.Tables) //{ // string str = B.Name; //} string name = user.Name; string pwd = user.PassWord; //var table = userInfo.Tables.FirstOrDefault(x => x.Name == user.Name); var table = userInfo.Tables.AsQueryable(); var info= table.FirstOrDefault(x => x.Name == user.Name); if (info != null) { //string url= Url.Action("Index", "Admin").ToString(); FormsAuthentication.SetAuthCookie(info.Name, false); //重新定向到Admin/Index页面 return Redirect(returnUrl??Url.Action("Index","Admin")); } else { return View(); } } }
html代码
@model SpotrsStore.Domain.Entities.Admin @{ ViewBag.Title = "Login2"; Layout = "~/Views/Shared/_AdminLayout.cshtml"; } <div class="panel"> <div class="panel-heading"> <h3>log in</h3> </div> <div class="panel-body"> <p class="lead">please log in access the administrator area</p> @using (Html.BeginForm()) { Html.ValidationSummary(); <div class="form-group"> <label>username</label> @Html.TextBoxFor(x => x.Name, new { @class = "form-control" }) </div> <div class="form-group"> <label>password</label> @Html.PasswordFor(x => x.PassWord, new { @class = "form-control" }) </div> <input type="submit" value="log in" class="btn btn-primary" /> } </div> </div>
配置文件代码
<authentication mode="Forms"> <forms loginUrl="~/Account/Login2"></forms> </authentication>
重新的定向的的页面的控制器要加 [Authorize]//授权属性,加在类名上面或动作方法上面视情况所选择