我正在使用MVC3,并将用户认证放在web.config文件中。这是绕过sqlserver身份验证。
代码如下web.config中所示:
<authentication mode="Forms"> <forms loginUrl="~/Account/logon" timeout="2880" > <credentials passwordFormat="Clear"> <user name="test123" password="test123" /> </credentials> </forms> </authentication>
* The user name or password provided is incorrect.
当我调试到AccountController.cs文件,失败在MembershipService.ValidateUser(model.UserName,model.Password)方法。
解决方法
如果您检查标准的ASP.NET MVC 3 AccountController.cs和AccountModels.cs文件,您将学习内部使用的
MembershipProvider.ValidateUser方法(通过
Membership.Provider)。如果要在web.config中存储密码,则应该使用
FormsAuthentication.Authenticate方法。
例如:
public class AuthorizationController : Controller { public ActionResult logon() { return View("logon"); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult logon(string userName,string password,bool rememberMe,string returnUrl) { if (!Validatelogon(userName,password)) return View("logon"); FormsAuthentication.SetAuthCookie(userName,rememberMe); if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index","News"); } private bool Validatelogon(string userName,string password) { if (string.IsNullOrEmpty(userName)) ModelState.AddModelError("username","User name required"); if (string.IsNullOrEmpty(password)) ModelState.AddModelError("password","Password required"); if (ModelState.IsValid && !FormsAuthentication. Authenticate(userName,password)) ModelState.AddModelError("_FORM","Wrong user name or password"); return ModelState.IsValid; } public RedirectToRouteResult logoff() { FormsAuthentication.SignOut(); return RedirectToAction("logon"); } }