在ASP.NET中,制作登录和用户信息最快捷的方式就是使用Membership,Role,Profile provide. 在使用他们的过程中,一般情况下需要在注册界面加上验证码功能来防止有人利用机器人之类的软件自动批量注册,
而这里将介绍怎样使用CreateUserWizard控件去做一个简单注册界面,当然你需要使用自己的数据表和其他功能的话,可以在这个sample上面添加,本samples实现了一些最基本的功能。
这个应用程序使用了CreateUserWizard的CreateUserWizardStep和CompleteWizardStep template来收集用户信息,并且添加验证码控件。同时,这里需要使用Sqlserver创建MDF的文件,所以你需要安装一个数据库,express版本的即可,这里是官方下载地址:
新建一个项目 ASP.NET Empty Web Application, 添加一个Web form, 命名为“Default.aspx”. 在aspx界面上创建一个CreateUserWizard控件,并且添加你想要的注册信息,本例的代码如下:
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:CreateUserWizard ID="CreateUserWizardName" runat="server" onnextbuttοnclick="CreateUserWizardName_NextButtonClick" oncreatinguser="CreateUserWizardName_CreatingUser"> <WizardSteps> <asp:CreateUserWizardStep ID="CreateUserWizardNameStep" runat="server"> <ContentTemplate> <table border="0" style="font-size: 100%; font-family: Verdana" mce_style="font-size: 100%; font-family: Verdana"> <tr> <td align="center" colspan="2" style="font-weight: bold; color: white; background-color: #5d7b9d" mce_style="font-weight: bold; color: white; background-color: #5d7b9d"> Sign Up for Your New Account </td> </tr> <tr> <td align="right"> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName"> User Name:</asp:Label> </td> <td> <asp:TextBox ID="UserName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password"> Password:</asp:Label> </td> <td> <asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword"> Confirm Password:</asp:Label> </td> <td> <asp:TextBox ID="ConfirmPassword" runat="server" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="ConfirmPassword" ErrorMessage="Confirm Password is required." ToolTip="Confirm Password is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email"> E-mail:</asp:Label> </td> <td> <asp:TextBox ID="Email" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email" ErrorMessage="E-mail is required." ToolTip="E-mail is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="QuestionLabel" runat="server" AssociatedControlID="Question"> Security Question:</asp:Label> </td> <td> <asp:TextBox ID="Question" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="QuestionRequired" runat="server" ControlToValidate="Question" ErrorMessage="Security question is required." ToolTip="Security question is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="AnswerLabel" runat="server" AssociatedControlID="Answer"> Security Answer:</asp:Label> </td> <td> <asp:TextBox ID="Answer" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="AnswerRequired" runat="server" ControlToValidate="Answer" ErrorMessage="Security answer is required." ToolTip="Security answer is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="right"> <asp:Label ID="lblCaptcha" runat="server" AssociatedControlID="codeNumberTextBox"> Code Number:</asp:Label> </td> <td> <asp:TextBox ID="codeNumberTextBox" runat="server"></asp:TextBox><asp:Label ID="lbMessage" runat="server" Text="Label"></asp:Label> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="CreateUserWizard1">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="center" colspan="2"> <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password" ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match." ValidationGroup="CreateUserWizard1"></asp:CompareValidator> </td> </tr> <tr> <td align="center" colspan="2" style="color: red" mce_style="color: red"> <asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal> </td> </tr> </table> </ContentTemplate> </asp:CreateUserWizardStep> <asp:CompleteWizardStep ID="CreateUserWizardComplete" runat="server"> <ContentTemplate> <center><asp:Label ID="lbTitle" runat="server" Text="Personal Information"></asp:Label></center><br /> User Name: <asp:Label ID="lbUserName" runat="server"></asp:Label><br /> E-mail: <asp:Label ID="lbEmail" runat="server"></asp:Label><br /> Question: <asp:Label ID="lbQuestion" runat="server"></asp:Label><br /> </ContentTemplate> </asp:CompleteWizardStep> </WizardSteps> </asp:CreateUserWizard> <asp:Label ID="lbError" runat="server" Font-Bold="True"></asp:Label> </div> </form> </body> </html>
这里的CreateUserWizardStep中显示的是最初看到的内容,而CompleteWizardStep显示的是点击创建用户完了看到的内容,比较简单
第二步 添加后台代码了, 首先我们要写一个生成随机数和字母的方法,用来生成随机代码,这里只是作为一个label的Text属性来显示,不安全,你可以把他生成为一张图片来显示(通过使用Graphics类)。有一个贴子,大家可以参考:
http://blog.csdn.net/21aspnet/archive/2007/03/20/1534392.aspx
生成随机数的方法GenerateRandomCode(),添加到Default.aspx.cs界面
// Used to create numbers randomly private string GenerateRandomCode() { string allChar = "1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"; int codeCount = 6; string[] allCharArray = allChar.Split('',''); string randomCode = ""; int temp = -1; Random rand = new Random(); for (int i = 0; i < codeCount; i++) { if (temp != -1) { rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); } int t = rand.Next(allCharArray.Length - 1); if (temp == t) { return GenerateRandomCode(); } temp = t; randomCode += allCharArray[t]; } // Set value to session variable when the function is called. Session["CaptchaImageText"] = randomCode; return randomCode; }
第三步,把下列代码添加到Default.aspx.cs页面的page_load事件中,这里比较简单,在第一次加载页面时生成验证码,同时定义了一个私有bool变量IsCreateSuc,在后面会用到
Page_Load事件代码(Default.aspx.cs)
private bool IsCreateSuc; protected void Page_Load(object sender, EventArgs e) { // Get label from CreateUserWizard control. Control ctrllbl = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("lbMessage"); if (ctrllbl != null) { if (!IsPostBack) { Label lbl = (Label)ctrllbl; string captchaCode = GenerateRandomCode(); this.Session["CaptchaImageText"] = captchaCode; lbl.Text = captchaCode; } } }
最后一步了,调用CreateUserWizard控件的两个方法NextButtonClick和CreatingUser,我使用的是vs2010开发,其他版本的vs不知道名称是否都一致,详细名称可以查询下MSDN。
这里CreateingUser事件,在创建新用户的时候触发,在这个事件中你可以添加自己的判断代码,比如这里就用到了验证我们生成的验证码是否和输入的匹配,如果不匹配,使用e.Cancal=true来取消创建用户的sql command, 如果你使用之后事件来写取消创建用户这个步骤是不行的(例如CreatedUser和NextButtonClick)。
例如:你把判断验证码的代码写在了NextButtonClick,也使用e.Cancal=true来返回,那么你也可以看到应用程序返回错误信息,但是在数据库中新用户创建成功了。
所以我们在CreateingUser事件中判断验证码是否匹配,并且传给私有的信号变量IsCreateSuc,通知下一步的事件返回成功信息,或者是保持在注册页面。
CreatingUser事件代码。(Default.aspx.cs)
/// <summary> /// Check the captcha code is matched. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CreateUserWizardName_CreatingUser(object sender, LoginCancelEventArgs e) { Control ctrl = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("codeNumberTextBox"); TextBox txb = (TextBox)ctrl; // You can check the user input like this: if (txb.Text == this.Session["CaptchaImageText"].ToString()) { this.IsCreateSuc = true; } else { this.IsCreateSuc = false; lbError.Text = "ERROR: Captcha code incorrect, please try again."; txb.Text = ""; e.Cancel = true; } }
NextButtonClick事件代码。(Default.aspx.cs)
/// <summary> /// After create a user account, display user''s basic information. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CreateUserWizardName_NextButtonClick(object sender, WizardNavigationEventArgs e) { if (IsCreateSuc) { // Display an informational message lbError.Text = "Create a new user"; // Display your information Control ctrlName = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("UserName"); string strUserName = ((TextBox)ctrlName).Text; Control ctrlPassword = CreateUserWizardName.CreateUserStep.ContentTemplateContainer.FindControl("Password"); string strPassword = ((TextBox)ctrlPassword).Text; Control ctrlLbUsername = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbUserName"); Control ctrlLbEmail = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbEmail"); Control ctrlLbQuestion = CreateUserWizardName.CompleteStep.ContentTemplateContainer.FindControl("lbQuestion"); MembershipUser userInfo; if (Membership.ValidateUser(strUserName, strPassword) == true) { userInfo = Membership.GetUser(strUserName); ((Label)ctrlLbUsername).Text = userInfo.UserName; ((Label)ctrlLbQuestion).Text = userInfo.PasswordQuestion; ((Label)ctrlLbEmail).Text = userInfo.Email; } } else { e.Cancel = true; } }
好了,那么你可以开始运行项目了。注意,第一次注册可能会比较慢,因为应用程序要在你的项目中创建一个db file。默认名字是ASPNETDB.MDF, 创建用户成功后, 会显示账户的基本信息.