C# 生成验证码 方法一

注意命名空间的引用

在项目中新建Validcode.aspx

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false"%>

<%@ Import Namespace="System.Drawing" %>

<%@ Import Namespace="System.Drawing.Drawing2D" %>

<%@ Import Namespace="System.Drawing.Imaging" %>

<%@ Import Namespace="System.IO" %>

<%@ Import Namespace="System.Text" %>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>验证码</title>

    <!--禁止浏览器从本地缓存中调阅页面-->

    <meta http-equiv="pragram" content="no-cache" />

    <!--必须重新加载页面-->

    <meta http-equiv="cache-control" content="no-cache, must-revalidate" />

    <!--网页在缓存中的过期时间-->

    <meta http-equiv="expires" content="-1" />

 

    <script type="text/C#" runat="server">

        /*

         * 使用方法

         * <img id="imgValidateCode" border="1" src="ValidateCode.aspx" style="cursor:hand" onclick="this.src='ValidateCode.aspx?'+Math.random()" title="点击更换验证码" />

         */

        static readonly char[] codeList = new char[]{'0','1','2','3','4','5','6','7','8','9'};

 

        string sessionKey = "ValidateCode";//保存在Session中所用的KEY

        int codeLength = 4;                //验证码字符长度  

        int width = 64;                   //验证码图片宽度

        int height = 20;                   //验证码图片高度

        int fontSize = 13;                 //验证码字体大小

 

        protected void Page_Load(object sender, EventArgs e)

        {

            //获取验证码字符串

            string strCode = GetValidateCode();

 

            //将验证码字符串保存到Session中

            Session[sessionKey] = strCode;

 

            //实例化图片

            using (Bitmap img = new Bitmap(width, height))

            {

                //获取画板

                using (Graphics g = Graphics.FromImage(img))

                {

                    //填充底纹

//                    g.FillRectangle(new HatchBrush(HatchStyle.Horizontal, Color.LightYellow, Color.LightSkyBlue), 0, 0, width, height);
                    g.Clear(Color.LightCyan);

                    Random rand = new Random();
                    for (int i = 0; i < 150; i++)
                    {
                        int x = rand.Next(img.Width);
                        int y = rand.Next(img.Height);
                        g.DrawPie(new Pen(Color.LightGray, 0f), x, y, 4, 4, 1, 1);
                    } 

                    //绘制验证码

                    using (Font font = new Font("Rockwell", fontSize, FontStyle.Bold | FontStyle.Italic))

                    {

                        g.DrawString(strCode, font, new LinearGradientBrush(new Point(0, 0), new Point(0, 5), Color.Blue, Color.Chocolate), (width - font.SizeInPoints * codeLength) / 2, (height - font.SizeInPoints) / 3);

                    }

                    using (MemoryStream mStream = new MemoryStream())

                    {

                        //将图片存入内存中

                        img.Save(mStream, ImageFormat.Gif);

 

                        //将图片输出至页面

                        Response.ClearContent();

                        Response.ContentType = "image/gif";

                        Response.BinaryWrite(mStream.ToArray());

                    }

                }

            }

            Response.End();

        }

 

 

        //生成验证码

        public string GetValidateCode()

        {

            Random rand = new Random();

            StringBuilder strBuilder = new StringBuilder(codeLength);

            for (int i = 0; i < codeLength; i++)

            {

                strBuilder.Append(codeList[rand.Next(0, codeList.Length)]);

            }

            return strBuilder.ToString();

        }

    </script>

</head>

<body>

</body>

</html>

客户端

<form id="form1" runat="server">
    <ul>
    <li><asp:TextBox ID="txt_LoginName" runat="server"   class="loginuser" ></asp:TextBox></li>
    <li><asp:TextBox ID="txt_PassWord" runat="server" class="loginpwd"  TextMode ="Password"></asp:TextBox></li>
              <li><label>验证码:</label><asp:TextBox ID="txt_CheckCode" runat="server" class="loginBox" style="width: 100px;" type="text" CssClass="loginCode" size="20" maxlength="15"></asp:TextBox>
              <img  align="absmiddle" id="Img1" style="cursor: pointer;"   src="Validcode.aspx?k=" alt="验证码" title="看不清,换张图片?" onclick="this.src+=Math.random();" /><label>点击图片刷新</label> </li>
<li> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                                            ErrorMessage="请输入登录名" 
        ControlToValidate="txt_LoginName" Display="Dynamic" Width="74px"></asp:RequiredFieldValidator>

                                        <asp:CustomValidator ID="CustomValidator1" runat="server" 
                                            ControlToValidate="txt_LoginName" 
        Display="Dynamic" ErrorMessage="登录名不正确" 
                                            
        onservervalidate="CustomValidator1_ServerValidate" Width="72px"></asp:CustomValidator>
                                            
                                            
                                                                                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                                            ErrorMessage="请输入密码" 
        ControlToValidate="txt_PassWord" Display="Dynamic" Width="62px"></asp:RequiredFieldValidator>

                                        <asp:CustomValidator ID="CustomValidator2" runat="server" 
                                            ControlToValidate="txt_PassWord" 
        Display="Dynamic" ErrorMessage="密码不正确" 
                                            
        onservervalidate="CustomValidator2_ServerValidate" Width="62px"></asp:CustomValidator>
                                            
                                                                                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                                                ErrorMessage="请输入验证码" 
        ControlToValidate="txt_CheckCode" Display="Dynamic" Width="73px" ></asp:RequiredFieldValidator>

                                            <asp:CustomValidator ID="CustomValidator3" runat="server" 
                                                ControlToValidate="txt_CheckCode" 
            Display="Dynamic" ErrorMessage="验证码不正确" 
                                                
            onservervalidate="CustomValidator3_ServerValidate" Width="73px"></asp:CustomValidator>
          </li>
    <li><asp:Button ID="Button1" runat="server" Text="登录" class="loginbtn" value="登录"  onclick="Button1_Click" /><label><input name="" type="checkbox" value="" checked="checked" />记住密码</label><label><a href="Reg.aspx">点此注册会员</a></label></li>
    </ul>
    
    </form>

服务端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;


public partial class Manage_Login : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string Password = txt_PassWord.Text.ToString().Trim().Replace("'", "''").Replace("=", "");
            string UserID = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");
            Password = func.md5(Password);
            string CheckCode = txt_CheckCode.Text.ToString().Trim();
            UserID = UserID.Replace("'", "''").Replace("=", "");
            string sql = "select * from DeviceUser where LoginName='" + UserID + "' and IsChecked = 1 ";
            DataTable dt = new DataTable();
            dt = db.GreatDs(sql).Tables[0];

            if (dt.Rows.Count > 0)
            {
                string pw1 = dt.Rows[0]["Password"].ToString();
                if (Password == dt.Rows[0]["Password"].ToString())
                {
                    string ID = dt.Rows[0]["ID"].ToString();
                     DateTime datetime = DateTime.Now;//定义时间对象
                    HttpCookie DeviceUserIDcookie = System.Web.HttpContext.Current.Response.Cookies["DeviceUserID"];
                    DeviceUserIDcookie.Values.Add("ID",dt.Rows[0]["ID"].ToString().Trim()) ;
                    DeviceUserIDcookie.Values.Add("LoginTime", datetime.ToString());
                    TimeSpan ts = new TimeSpan(1, 0, 0, 0);//cookie有效作用时间,具体查msdn
                    DeviceUserIDcookie.Expires = datetime.Add(ts);//添加作用时间

                    System.Web.HttpContext.Current.Response.AppendCookie(DeviceUserIDcookie);//确定写入cookie中
                    
                    Response.Redirect("index.aspx");
                }
            }
        }
    }
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {


        string LoginName = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");
        LoginName = LoginName.Replace("'", "''").Replace("=", "");
        string sql = "select count(id) from DeviceUser  where LoginName='" + LoginName + "'  and IsChecked = 1 ";
        int Count = int.Parse(db.ExeSQLs(sql));
        if (Count == 0)
        {
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;

        }


    }
    protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string Password = txt_PassWord.Text.ToString().Trim().Replace("'", "''").Replace("=", "");
        string LoginName = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");
        Password = func.md5(Password);
        string CheckCode = txt_CheckCode.Text.ToString().Trim();




        LoginName = LoginName.Replace("'", "''").Replace("=", "");
        string sql = "select * from DeviceUser   where LoginName='" + LoginName + "'  ";
        DataTable dt = new DataTable();
        dt = db.GreatDs(sql).Tables[0];
        if (dt.Rows.Count > 0)
        {
            string pw1 = dt.Rows[0]["Password"].ToString();
            if (Password == pw1)
            {
                args.IsValid = true;

            }
            else
            {
                args.IsValid = false;
            }
        }
        else
        {
            args.IsValid = true;
        }

    }
    protected void CustomValidator3_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (args.Value != "")
        {
            string CheckCode = args.Value;
            string ValidateCodeSession = "";
            if (Session["ValidateCode"] != null)
            {
                ValidateCodeSession = Session["ValidateCode"].ToString();
            } 
            
            if (CheckCode == ValidateCodeSession)
            {
                args.IsValid = true;

            }
            else
            {
                args.IsValid = false;

            }
        }
    }


}

 

posted @ 2016-06-30 16:01  I'm莫小妞丶  阅读(615)  评论(0编辑  收藏  举报