# 會員注冊與登錄模塊


首先分別新建三個網頁,register.aspx,login.aspx, yzm.aspx分別用於用戶的注冊,登錄以及驗證碼的生成。

 

register.aspx前台代碼:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="register.aspx.cs" Inherits="_Default" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title>注冊頁面</title>
 9     <style type ="text/css">
10         .wrap {
11             padding-top:40px;
12             margin:0 auto;
13             width:760px;
14             height:426px;
15         }
16         .auto-style1 {
17             width: 399px;
18         }
19     </style>
20 </head>
21 <body>
22     <form id="form1" runat="server">
23         <table>
24             <tr>
25                 <td>用戶名:</td><td class="auto-style1"><asp:TextBox ID ="txtName"  runat ="server" AutoPostBack="true" OnTextChanged ="txtName_TextChanged"></asp:TextBox><asp:Label ID ="labuser" runat ="server"></asp:Label></td>
26             </tr>
27             <tr>
28                 <td>密碼:</td><td class="auto-style1"><asp:TextBox ID ="txtPass"  runat ="server" TextMode ="Password" Width="149px"></asp:TextBox></td>
29             </tr>
30             <tr>
31                 <td>重復密碼:</td><td class="auto-style1"><asp:TextBox ID ="txtQpass"  runat ="server" TextMode ="Password" Width="149px"></asp:TextBox></td>
32             </tr>
33             <tr>
34                 <td>昵稱:</td><td class="auto-style1"><asp:TextBox ID ="txtNickName"  runat ="server"></asp:TextBox></td>
35             </tr>
36             <tr>
37                 <td>性別:</td><td class="auto-style1"><asp:RadioButton ID ="radnan" runat ="server" Text ="" GroupName ="sex" Width ="80px"/><asp:RadioButton ID ="radnv" runat ="server" Text ="" GroupName ="sex" Width ="80px"/></td>
38             </tr>
39             <tr>
40                 <td>電話:</td><td class="auto-style1"><asp:TextBox ID ="txtPhone"  runat ="server"></asp:TextBox></td>
41             </tr>
42             <tr>
43                 <td>E-mail:</td><td class="auto-style1"><asp:TextBox ID ="txtEamil"  runat ="server"></asp:TextBox></td>
44             </tr>
45             <tr>
46                 <td>所在城市:</td><td class="auto-style1"><asp:TextBox ID ="txtCity"  runat ="server"></asp:TextBox></td>
47             </tr>
48             <tr>
49                 <td><asp:Button ID ="btnregister" runat ="server" Text ="注冊" OnClick ="btnregister_Click"/></td><td class="auto-style1"><asp:Button ID ="btnreturn" runat ="server" Text="返回" PostBackUrl ="~/Default.aspx" CausesValidation ="true"/></td>
50             </tr>
51         </table>
52     </form>
53 </body>
54 </html>

 

 

register.aspx.cs后台代碼:

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Web.UI;
  6 using System.Web.UI.WebControls;
  7 
  8 using System.Data;
  9 using System.Web.Security;
 10 using System.Configuration;
 11 using System.Data.SqlClient;
 12 using System.Text.RegularExpressions;
 13 
 14 public partial class _Default : System.Web.UI.Page
 15 {
 16     protected void Page_Load(object sender, EventArgs e)
 17     {
 18     }
 19 
 20     /// <summary>
 21     /// 當焦點移出文本框時,判斷用戶是否存在,以及輸入的字符格式是否符合規定.
 22     /// </summary>
 23     /// <param name="sender"></param>
 24     /// <param name="e"></param>
 25     protected void txtName_TextChanged(object sender, EventArgs e)
 26     {
 27         if (this.txtName.Text == "")
 28         {
 29             //如果沒有輸入用戶名,則提示用戶名不能為空.
 30             this.labuser.Text = " * 用戶名稱不能為空!";
 31 
 32             //改變提示lable控件文字的顏色.
 33             this.labuser.ForeColor = System.Drawing.Color.Red;
 34         }
 35         else
 36         {
 37             if (isnameFormar())//調用isnameFormar方法,判斷用戶名是否符合格式要求.
 38             {
 39                 if (isName())//調用iaName方法,判斷用戶名是否已經存在.
 40                 {
 41                     //已經注冊,則提示.
 42                     this.labuser.Text = " * 該用戶已經注冊!";
 43 
 44                     //改變提示lable控件文字的顏色.
 45                     this.labuser.ForeColor = System.Drawing.Color.Red;
 46                 }
 47                 else
 48                 {
 49                     //沒有注冊,則提示可以注冊.
 50                     this.labuser.Text = " * 可以注冊!";
 51 
 52                     //改變提示lable控件文字的顏色.
 53                     this.labuser.ForeColor = System.Drawing.Color.Red;
 54                 }
 55             }
 56             else
 57             {
 58                 //格式不對,則提示
 59                 this.labuser.Text = " * 用戶名格式不對!";
 60 
 61                 //改變提示lable控件文字的顏色.
 62                 this.labuser.ForeColor = System.Drawing.Color.Red;
 63             }
 64         }
 65     }
 66 
 67     /// <summary>
 68     /// 注冊按鈕的事件
 69     /// </summary>
 70     /// <param name="sender"></param>
 71     /// <param name="e"></param>
 72     protected void btnregister_Click(object sender, EventArgs e)
 73     {
 74         if (isnameFormar())
 75         {
 76             if (isName())
 77             {
 78                 this.labuser.Text = "用戶名已經存在!";
 79 
 80                 this.labuser.ForeColor = System.Drawing.Color.Red;
 81 
 82                 RegisterStartupScript("", "<script>alert('請輸入正確信息!')</script>");//不報錯,但是已過時,在.NET3.5和4.0中有更好的方法替代他們。
 83             }
 84             else
 85             {
 86                 //獲取用戶名
 87                 string username = this.txtName.Text.Trim();
 88 
 89                 //獲取用戶填寫的密碼,並用MD5進行加密.
 90                 string userpass = FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtPass.Text, "MD5");//不報錯,但是已過時,在.NET3.5和4.0中有更好的方法替代他們。
 91 
 92                 //獲取昵稱
 93                 string nickname = this.txtNickName.Text;
 94 
 95                 //獲取性別
 96                 string sex = string.Empty;
 97                 if (this.radnan.Checked)
 98                 {
 99                     sex = "";
100                 }
101                 else if (this.radnv.Checked)
102                 {
103                     sex = "";
104                 }
105                 else { }
106 
107                 //獲取電話號碼
108                 string phone = this.txtPhone.Text;
109 
110                 //獲取電子郵件地址
111                 string Email = this.txtEamil.Text;
112 
113                 //獲取所在城市
114                 string city = this.txtCity.Text;
115 
116                 string strcon = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;//連接數據庫.
117 
118                 using (SqlConnection con = new SqlConnection(strcon))
119                 {
120                     if (con.State == ConnectionState.Closed)
121                     {
122                         con.Open();
123                     }
124 
125                     SqlParameter[] paras = new SqlParameter[] 
126                     {
127                         new SqlParameter("@username", username),
128                         new SqlParameter("@userpass", userpass),
129                         new SqlParameter("@nickname", nickname),
130                         new SqlParameter("@sex", sex),
131                         new SqlParameter("@phone", phone),
132                         new SqlParameter("@Email", Email),
133                         new SqlParameter("@city", city)
134                     };
135 
136                     string sql = "insert into tb_User (userName, userPass, nickName, sex, phone, E_mail, city) values (@username, @userpass, @nickname, @sex, @phone, @Email, @city);";
137 
138                     SqlCommand cmd = new SqlCommand(sql, con);
139 
140                     cmd.Parameters.AddRange(paras); 
141 
142                     if (Convert.ToInt32(cmd.ExecuteNonQuery()) > 0)
143                     {
144                         RegisterStartupScript("", "<script>alert('注冊成功!')</script>");
145 
146                         this.txtName.Text = this.txtPass.Text = this.txtQpass.Text = "";
147                         this.txtNickName.Text = this.txtPhone.Text = this.txtEamil.Text = this.txtCity.Text = "";
148                         this.labuser.Text = "";
149                     }
150                     else
151                     {
152                         RegisterStartupScript("", "<script>alert('請輸入正確格式!')</script>");
153                     }
154                 }
155             }
156         }
157         else
158         {
159             RegisterStartupScript("", "<script>alert('請輸入正確格式!')</script>");
160         }
161     }
162 
163     /// <summary>
164     /// 判斷用戶名是否符合格式要求.
165     /// </summary>
166     /// <returns></returns>
167     public bool isnameFormar()
168     {
169         bool flag = false;
170 
171         //設置正則表達式.(使用此對象要導入 System.Text.RegularExpressions命名空間)
172         Regex re = new Regex("^\\w+$");
173 
174         if (re.IsMatch(this.txtName.Text.Trim()))
175         {
176             flag = true;//返回flag為真.
177         }
178 
179         return flag;
180     }
181 
182     /// <summary>
183     /// 判斷用戶名是否已經存在
184     /// </summary>
185     /// <returns></returns>
186     public bool isName()
187     {
188         bool flag = false;
189 
190         string strcon = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;//連接數據庫.
191 
192         using (SqlConnection con = new SqlConnection(strcon))
193         {
194             if (con.State == ConnectionState.Closed)
195             {
196                 con.Open();
197             }
198 
199             SqlParameter[] paras = new SqlParameter[]
200             {
201                 new SqlParameter("@userName", this.txtName.Text.Trim())
202             };
203 
204             string sql = "select * from tb_User where userName = @userName ";
205 
206             SqlCommand cmd = new SqlCommand(sql, con);
207 
208             cmd.Parameters.AddRange(paras);
209 
210             if ( Convert.ToInt32(cmd.ExecuteScalar()) > 0)//如果返回值大於0,則表示用戶已經存在.
211             {
212                 flag = true;
213             }
214         }
215 
216         return flag;
217     }
218 }

 

以上是注冊頁面的編寫,下面是登錄頁面的編寫:

 

 

login.aspx代碼:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" Debug ="true"%>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title></title>
 9     <style type ="text/css">
10         #imagecode {
11             text-align:left;
12         }
13     </style>
14 </head>
15 <body>
16     <form id="form1" runat="server">
17     <div>
18     <table>
19         <tr>
20             <td>用戶名:</td><td><asp:TextBox ID ="txtname" runat ="server"></asp:TextBox></td>
21         </tr>
22         <tr>
23             <td>密碼:</td><td><asp:TextBox ID ="txtpass" runat ="server" TextMode ="Password"></asp:TextBox></td>
24         </tr>
25         <tr>
26             <td>驗證碼:</td><td><asp:TextBox ID ="yzm" runat ="server" Width ="60px"></asp:TextBox><img id ="imagecode" src ="yzm.aspx" alt ="看不清!請點擊刷新!" onclick ="this.src=this.src+'?'" />
27         </tr>
28         <tr>
29             <td style ="text-align:center"><asp:Button ID ="txtCode" runat ="server" Text ="登陸" OnClick ="txtCode_Click1"/></td><td style ="text-align:center"><asp:Button ID ="cz" runat ="server" Text ="重置" /></td>
30         </tr>
31     </table>
32     </div>
33     </form>
34 </body>
35 </html>

 

login.aspx.cs代碼:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 using System.Data;
 9 using System.Web.Security;
10 using System.Data.SqlClient;
11 using System.Configuration;
12 
13 public partial class login : System.Web.UI.Page
14 {
15     protected void Page_Load(object sender, EventArgs e)
16     {
17         
18     }
19 
20     protected void txtCode_Click1(object sender, EventArgs e)
21     {
22         string code = this.yzm.Text;
23 
24         if (Request.Cookies["checkcode"].Value == code)
25         {
26             string strcon = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
27 
28             using (SqlConnection con = new SqlConnection(strcon))
29             {
30                 if (con.State == ConnectionState.Closed)
31                 {
32                     con.Open();
33                 }
34 
35                 string pass = FormsAuthentication.HashPasswordForStoringInConfigFile(this.txtpass.Text, "MD5");
36 
37                 SqlParameter[] paras = new SqlParameter[]
38                 {
39                     new SqlParameter("@pass", pass),
40                     new SqlParameter("@name", this.txtname.Text)
41                 };
42 
43                 string sql = "select * from tb_User where userName = @name and userPass = @pass";
44 
45                 SqlCommand cmd = new SqlCommand(sql, con);
46 
47                 cmd.Parameters.AddRange(paras);
48 
49                 if (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
50                 {
51                     RegisterStartupScript("", "<script>alert('登錄成功!')</script>");
52                     //清空文本框
53                     txtpass.Text = yzm.Text = txtname.Text = "";
54                 }
55                 else
56                 {
57                     RegisterStartupScript("", "<script>alert('用戶名或密碼錯誤!')</script>");
58                 }
59             }
60         }
61         else
62         {
63             RegisterStartupScript("", "<script>alert('驗證碼錯誤!')</script>");
64         }
65     }
66 }

 

以上是登錄頁面的編寫,下面是驗證碼的編寫:

 

yzm.aspx代碼(並沒有使用一般處理程序):

  -yzm.aspx前台代碼不需要編寫。

 

yzm.aspx.cs代碼:

protected void Page_Load(object sender, EventArgs e)
{
    createyzm(random());
}

/// <summary>
/// 這個方法是用於生成隨機數
/// </summary>
/// <returns>生成的隨機數</returns>
public string random()
{
    int number;//創建一個整型變量,用於存儲的單個隨機數.

    char a = new char();//創建一個字符變量,用於存儲有整型轉換成字符型的變量.

    string b = string.Empty;//創建一個字符串變量,用於存儲生成的隨機數字符串.

    Random rm = new Random();//創建一個隨機數對象rm, 用於獲取隨機數.

    //循環,用於生成單個隨機數,以及把單個隨機數,拼合成字符串.
    for (int i = 0; i < 4; i++)
    {
        number = rm.Next();//生成隨機數.

        a = (char)('0' + (char)(number % 10));//把生成的隨機數,無論是多大,只要除於10,得到的余數都是個位數,然后把他們轉換成char類型的字符.

        b += a.ToString();//把獲得的單個字符,累加成一個字符創,其中一定要把,字符類型,轉換成字符串類型.
    }

    Response.Cookies.Add(new HttpCookie("checkcode", b));//把生成的隨機數字符串,放到創建的名為checkcode的cookies中,以便於,其他頁面的調用時獲取.

    return b;//同時把生成的隨機數返回(傳出),以便於驗證碼制作.
}

/// <summary>
/// 這個方法是用於制作驗證碼
/// </summary>
/// <param name="sjs">接收random()方法生成的隨機數</param>
public void createyzm(string sjs)
{
    if (null == sjs && sjs.Trim() == string.Empty)
    {
        return;
    }

    System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling(sjs.Length * 12.5), 22);//方法的重載,用於制定的大小初始化System.Drawing.Bitmap類的新實例,第一個參數是寬,第二個參數是高,單位是像素.

    Graphics g = Graphics.FromImage(image);//從指定的 System.Drawing.Image 創建新的 System.Drawing.Graphics。

    try
    {
        Random random = new Random();//創建隨機數生成器.

        g.Clear(Color.White);//清空背景色.

        //繪制噪音線
        for (int i = 0; i < 10; i++)
        {
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);

            g.DrawLine(new Pen(Color.FromArgb(random.Next())), x1, x2, y1, y2);//繪制一條連接由坐標對指定的兩個點的線條。顏色是隨機的使用color.fromArgb(random.Next())。
        }

        Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));//設置文本的字體、字號和字形。

        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Width), Color.Blue, Color.OliveDrab, 1.2f, true);//設置繪制線條的線性漸變.

        g.DrawString(sjs, font, brush, 2, 2);//在指定位置並且用指定的 System.Drawing.Brush 和 System.Drawing.Font 對象繪制指定的文本字符串。

        //繪制噪音點
        for (int i = 0; i < 100; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);

            image.SetPixel(x, y, Color.FromArgb(random.Next()));//繪制隨機點,其中顏色也是隨機的.
        }

        //繪制驗證碼邊框線
        //參數一:確定矩形的顏色,寬度,和樣式。
        //參數二:要繪制的矩形的左上角的x坐標。
        //參數三:要繪制矩形的左上角y的坐標。
        //參數四:要繪制矩形的寬度。
        //參數五:要繪制矩形的高度。
        g.DrawRectangle(new Pen(Color.Black), 0, 0, image.Width - 1, image.Height - 1);

        //輸出到頁面上
        System.IO.MemoryStream ms = new System.IO.MemoryStream();//創建支持存儲區為內存的流。

        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);//將圖像以指定的格式保存到指定的流中。其中ImageFormat的作用是指定圖像的文件格式。

        Response.ClearContent();//清除緩沖區流中的所有內容輸出。

        Response.ContentType = "image/Gif";//獲取或設置輸出流的 http mime 類型。

        Response.BinaryWrite(ms.ToArray());//將二進制字符串寫入 http 輸出流。
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        g.Dispose();//釋放其使用的資源
        image.Dispose();//釋放其使用的資源.
    }
}

 

粘貼到,代碼內部即可。

以上就是會員注冊和登錄模塊編寫過程,寫下來便於以后學習。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM