欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

有验证码的登陆界面(ajax,ashx技术制作)

程序员文章站 2022-04-03 16:58:12
前提:要引用AjaxPro.2.dll(右键--添加引用---选AjaxPro.2.dll文件即可) 备注:程序中的红色部分是经常会搞错的地方,请大家重点关注下。  ...

前提:要引用AjaxPro.2.dll(右键--添加引用---选AjaxPro.2.dll文件即可)

备注:程序中的红色部分是经常会搞错的地方,请大家重点关注下。

 

1、首先制作ashx文件,功能(产生验证码图片,并把验证码保存在Session中,便于以后比对。

[ VDC.ashx ]文件
using System;
using System.Web;
using System.Drawing;
namespace TestExtjsJson.ashx
{
    /// <summary>
    /// VDC 的摘要说明
    /// </summary>
    public class VDC : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        //产生验证码的字符集(去除I 1 l L,O 0等易混字符)
        public string charSet = "2,3,4,5,6,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,R,S,U,W,X,Y";

        public void ProcessRequest(HttpContext context)
        {
            string validateCode = CreateRandomCode(4);
            //context.Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));//保存到Cookies 里,但前提对方浏览器允许Cookies操作!
            context.Session["CheckCode"] = validateCode;       //保存到Session中
            CreateImage(validateCode, context);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="n">位数</param>
        /// <returns>验证码字符串</returns>
        private string CreateRandomCode(int n)
        {
            string[] CharArray = charSet.Split(',');
            string randomCode = "";
            int temp = -1;

            Random rand = new Random();
            for (int i = 0; i < n; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(CharArray.Length - 1);
                if (temp == t)
                {
                    return CreateRandomCode(n);
                }
                temp = t;
                randomCode += CharArray[t];
            }
            return randomCode;
        }

        private void CreateImage(string checkCode, HttpContext context)
        {
            int iwidth = (int)(checkCode.Length * 13);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 23);
            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold));

            // 前景色
            Brush b = new System.Drawing.SolidBrush(Color.Black);

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

            // 填充文字
            g.DrawString(checkCode, f, b, 0, 1);

            // 随机线条
            Pen linePen = new Pen(Color.Gray, 0);
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                int x1 = rand.Next(image.Width);
                int y1 = rand.Next(image.Height);
                int x2 = rand.Next(image.Width);
                int y2 = rand.Next(image.Height);
                g.DrawLine(linePen, x1, y1, x2, y2);
            }

            // 随机点
            for (int i = 0; i < 30; i++)
            {
                int x = rand.Next(image.Width);
                int y = rand.Next(image.Height);
                image.SetPixel(x, y, Color.Gray);
            }

            // 边框
            g.DrawRectangle(new Pen(Color.Gray), 0, 0, image.Width - 1, image.Height - 1);

            // 输出图片
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
    }
}

2、编写登陆界面:testlogin.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestLogin.aspx.cs" Inherits="TestExtjsJson.TestLogin" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>威威ERP管理系统--登 陆</title>
     <link  rel="stylesheet" type="text/css" href="CSS/css.css" />
     <script type="text/javascript">
         function check() {
             var userName = document.getElementById("TxtName").value;
             var userPwd = document.getElementById("TxtPwd").value;
             if (TestExtjsJson.TestLogin.isRight(userName , userPwd ).value > 0) {         //引用函数时一定要写全名称(命名空间.类名.函数)
                 alert("登陆成功!!");
                 // TestLogin.WriteSession(userName + "");
                 //window.location.href = 'Index.aspx';
             }
             else {
                 alert("用户名或密码不正确!");
             }

         }
         function checkcode() {
             var TxtCode = document.getElementById("TxtCode").value;
             var _str = TestExtjsJson.TestLogin.CheckCode(TxtCode).value;
             if (_str == "YES") {
                 alert("验证码正确!!");
                 check();
             }
             else {
                 alert("出错!验证码错误!");
             }
         }
     </script>
</head>
<body style=" text-align:center">
    <form id="Form1" runat="server">
    <p style="text-align: center;  border-width:10px; border-color:blue; width:491px; height:318px; position: relative; top: 120px; left: 31px;">
        <img alt="" src="Images/Logintop.jpg" style="height: 169px; width: 492px" />
        <p style="left: 119px; width: 272px; position: relative; top: 10px; height: 0px">
            <p style="width: 322px; height: 25px; text-align: left">
                <span style="font-size: 10pt"> <span>帐 &nbsp;号:<asp:TextBox ID="TxtName" type="text"
                    runat="server"></asp:TextBox>
                </span></span></p>
            <p style="width: 322px; height: 25px; text-align: left">
                <span style="font-size: 10pt"><span>密 &nbsp;码:<asp:TextBox ID="TxtPwd"
                    runat="server"></asp:TextBox>
                </span></span></p>
            <p style="width: 322px; height: 25px; text-align: left">
                <span style="font-size: 11pt"> <span style="font-size: 10pt">验证码:</span></span><asp:TextBox ID="TxtCode" runat="server" Width="74px"></asp:TextBox>
                &nbsp;<asp:Image ID="Image1" runat="server"
                        Height="20px" ImageUrl="ashx/VDC.ashx"
                    Style="left: 0px; position: relative; top: 3px; width: 64px;" />
                <input id="Eyes" style="width: 44px; height: 21px" type="button" onclick="javascript:window.location.reload();" value="看不清" class="btn" /></p>
            <p style="width: 320px; height: 35px">
            </p>
            <p style="width: 320px; height: 33px; text-align: left;">
                &nbsp;
                <input id="Login" type="button" value="登  陆"  onclick="checkcode();" style="width: 75px" class="btn"/>
                &nbsp; &nbsp;&nbsp; &nbsp;
                <input id="Reset" style="width: 75px" type="reset" value="重  置" class="btn" /></p>
        </p>
        </p>
    </form>
</body>
</html>


3、编写登陆界面的代码部分:testlogin.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestExtjsJson
{
    public partial class TestLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //注册ajax
            if (!Page.IsPostBack)
            {
                AjaxPro.Utility.RegisterTypeForAjax(typeof(TestExtjsJson.TestLogin));     //注册时一定要写  命名空间.类名
            }
        }

        //判断用户名密码是否正确
        [AjaxPro.AjaxMethod]           //该方式不能读写Session
        public int isRight(string userName, string userPwd)
        {
            int count = 0;
            if (userName == "system" && userPwd == "8246")
            {
                count = 1;
            }
            else {
                count = 0;
            }
            return count;

           /*
              //对于 Applciation,和request的操作 不能直接读取,得前缀HttpContext.Current

              string str1=Application["App"];  //error
              string str2=Request["Req"];  //error   
              string str3=HttpContext.Current.Application["App"];   //right
              string str3=HttpContext.Current.Request["Req"];       //right

           */
        }

        //判断验证码是否正确
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)] //  可以读写Session:
        public string CheckCode(string checkcode)
        {
            string _checkcode = "NO";
            if (Session["CheckCode"].ToString().ToUpper() == checkcode)
            {
                _checkcode = "YES";
            }
            else {
                _checkcode = "NO";
            }
            return _checkcode;
        }
    }
}