asp.net MVC中如何用Membership类和自定义的数据库进行登录验证
asp.net MVC 内置的membershipProvider可以实现用户登陆验证,但是它用的是自动创建的数据库,所以你想用本地数据库数据去验证,是通过不了的。
如果我们想用自己的数据库的话,可以写自己的membershipProvider!下面介绍如果创建自己的membershipProvider:
1.写自己的MembershipProvider类,这个类继承自命名空间System.Web.Security下的MembershipProvider类
这个类放在哪无所谓,这里我放在新建MyCode文件夹里,然后新建类,取名为MyMembershipProvider,代码如下:
using System.Web.Security;namespace MvcWeb.MyCode { //自定义类,继承System.Web.Security.MembershipProvider public class MyMembershipProvider: MembershipProvider { } }
现在加代码进去,把鼠标光标放在MembershipProvider上,右键选择“实现抽象类”
实现抽象类后会有很多方法,这里只用到最后一个方法代码如下:
using System.Data.SqlClient; namespace MvcFeiGeTe.MyCode { //自定义类,继承System.Web.Security.MembershipProvider public class MyMembershipProvider: MembershipProvider { public override bool ValidateUser(string username, string password) { throw new NotImplementedException(); } } }
下面是填充上面方法的代码:
public override bool ValidateUser(string username, string password) { SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=MyDb;Integrated Security=True;user id=sa;password=admin123"); SqlCommand sqlcmd = new SqlCommand("select userName,passWord from adminInfo where userName = @userName and passWord = @passWord", sqlconn); try { sqlconn.Open(); sqlcmd.Parameters.Add(new SqlParameter("@userName", SqlDbType.NVarChar, 30)); sqlcmd.Parameters["@userName"].Value = username.Trim(); sqlcmd.Parameters.Add(new SqlParameter("@passWord", SqlDbType.NVarChar, 50)); sqlcmd.Parameters["@passWord"].Value = password.Trim(); SqlDataReader sqlRd = sqlcmd.ExecuteReader(); if (sqlRd.HasRows) { return true; } return false; } catch (Exception ex) { throw new Exception(ex.Message); } }
2.配置Web.config
把此配置文件下的<system.web>节点下的默认的<membership>节点换成如下(注意下划线部分):
<membership defaultProvider="MyMembershipProvider"> <providers> <add name="MyMembershipProvider" type="MvcWeb.MyCode.MyMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" /> </providers> </membership>
3.验证
在AccountController中:
if (ModelState.IsValid) { string password = FormsAuthentication.HashPasswordForStoringInConfigFile(model.passWord, "md5"); //加密 MyMembershipProvider mmsp = new MyMembershipProvider(); //自定义MyMembershipProvider,继承mvc自带的MembershipProvider,实现登陆验证,添加引用using MvcWeb.MyCode; if (mmsp.ValidateUser(model.userName, password)) { FormsAuthentication.SetAuthCookie(model.userName, true); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Admin"); } } else { ModelState.AddModelError("", "用户名或密码输入有误"); } }
ok!