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

asp.net验证码实现

程序员文章站 2022-05-13 09:50:04
...
//cs页面

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;

namespace RecruitmentSystem
{
public partial class RandomImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

CreateCheckCodeImage(GenerateCheckCode());
}
/// <summary>
/// 生成随机校验码字符串
/// </summary>
/// <returns>生成的随机校验码字符串</returns>
private string GenerateCheckCode()
{
int number;
string strCode = string.Empty;

//随机数种子
Random random = new Random();

for (int i = 0; i < 4; i++) //校验码长度为4
{
//随机的整数
number = random.Next();

//字符从0-9,A-Z中随机产生,对应的ASCII码分别为
//48-57,65-90
number = number % 36;
if (number < 10)
{
number += 48;
}
else
{
number += 55;
}
strCode += ((char)number).ToString();
}

//在session中保存校验码
Session["CheckCode"] = strCode;
return strCode;
}

/// <summary>
/// 根据校验码输出图片
/// </summary>
/// <param name="checkCode">产生的随机校验码</param>
private void CreateCheckCodeImage(string checkCode)
{
//若校验码为空,则直接返回
if (checkCode == null || checkCode.Trim() == String.Empty)
{
return;
}
//根据校验码的长度确定输出图片的长度
System.Drawing.Bitmap image = new System.Drawing.Bitmap(55, 20);//(int)Math.Ceiling(Convert.ToDouble(checkCode.Length * 15))
//创建Graphics对象
Graphics g = Graphics.FromImage(image);
try
{
//生成随机数种子
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线 10条
//---------------------------------------------------
for (int i = 0; i < 10; i++)
{
//噪音线起点坐标(x1,y1),终点坐标(x2,y2)
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.Silver), x1, y1, x2, y2);
}
//---------------------------------------------------
//Brush b = Brushes.Silver;
//g.FillRectangle(b, 0, 0, image.Width, image.Height);
//---------------------以上两种任选其一------------------------------
//输出图片中校验码的字体: 12号Arial,粗斜体
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));

//线性渐变画刷
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Purple, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);

//画图片的前景噪音点 50个
for (int i = 0; i < 50; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}

//画图片的边框线
g.DrawRectangle(new Pen(Color.Peru), 0, 0, image.Width - 1, image.Height - 1);

//创建内存流用于输出图片
using (MemoryStream ms = new MemoryStream())
{
//图片格式指定为png
image.Save(ms, ImageFormat.Jpeg);
//清除缓冲区流中的所有输出
Response.ClearContent();
//输出流的HTTP MIME类型设置为"image/Png"
Response.ContentType = "image/Jpeg";
//输出图片的二进制流
Response.BinaryWrite(ms.ToArray());
}
}
finally
{
//释放Bitmap对象和Graphics对象
g.Dispose();
image.Dispose();
}
}
}
}

  aspx页面不需要托任何控件或代码

 

引用验证码页面 页面cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;

namespace RecruitmentSystem.Jobhunters
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void BtnLogin_Click(object sender, EventArgs e)
        {
            if (string.Compare(Session["CheckCode"].ToString(), this.TexChecknum.Text.Trim(), true) == 0)
            {
               LabCheckNum.Text = "验证码正确!";
            }
            else
            {
                LabCheckNum.Text = "验证码错误!";
            }
        }
    }
}

  

aspx页面

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="RecruitmentSystem.Jobhunters.Login" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<span class="style5">验证码:</span><asp:TextBox ID="TexChecknum" runat="server" Width="44px"></asp:TextBox> <asp:Image ID="Image1" runat="server" ImageUrl="RandomImage.aspx" Height="19px" Width="50px"/> <asp:LinkButton ID="LinkButtonUpdate" runat="server" CausesValidation="False">换一张</asp:LinkButton> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="TexChecknum" runat="server" ErrorMessage="您还没有输入验证码"></asp:RequiredFieldValidator> </asp:Content>

  

 

转载于:https://www.cnblogs.com/RockyZhang/archive/2012/04/25/2470566.html

上一篇: .NET验证码

下一篇: 前端下载文件