紧接上一篇,废话不多说,直接上例子
实现1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
namespace PPLTest
{
public partial class creatCoad : System.Web.UI.Page
{
/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y' };
protected void Page_Load(object sender, EventArgs e)
{
//取消缓存
Response.BufferOutput = true;
Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AppendHeader("Pragma", "No-Cache");
//获取设置参数
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
{
validateCodeType = Request.QueryString["validateCodeType"];
}
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
{
int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
}
//生成验证码
this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < validateCodeCount; i++)
{
code = character[random.Next(character.Length)];
// 要求全为数字或字母
if (validateCodeType == "1")
{
if ((int)code < 48 || (int)code > 57)
{
i--;
continue;
}
}
else if (validateCodeType == "2")
{
if ((int)code < 65 || (int)code > 90)
{
i--;
continue;
}
}
checkCode += code;
}
Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
this.Session["CheckCode"] = checkCode;
return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
try
{
//生成随机生成器