建立通用功能类 Common.cs
在此类中添加生成随机字符串和字符串转换图片输出的函数
内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
namespace Cartoon
{
public class Common
{
//获取一个随机字符串
public static string GetRandom(int n)
{
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghizklmnopqrstuvwxyz1234567890";
Random random = new Random();
//生成n位随机数
string result = string.Empty;
for (int i = 1; i <= n; i++)
{
result += str[random.Next(0, str.Length - 1)].ToString();
}
return result;
}
//字符串转换图片
public static void DisplayImage(string str)
{
//使用cookies或session传值,用于验证验证码
//session
HttpContext.Current.Session["code"] = str;
//cookies
System.Web.HttpContext.Current.Response.Cookies["code"].Value = str;
//创建一个图片区域设置宽度和高度
Bitmap image = new Bitmap(50, 20);
//获取这个图片区域,便于在其中添加元素
Graphics g = Graphics.FromImage(image);
//设置图片背景为白色
g.Clear(Color.White);
//画线构造一些盲点,意思就是让图片显示不清楚
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int x2 = random.Next(image.Width);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
//定义字体对象,设置字体大小
Font font = new Font("黑体", 12);
//定义画笔颜色
SolidBrush brush = new SolidBrush(Color.BlueViolet);
//定义画笔写信息的位置坐标点,为左上角(0,0)点
PointF point = new PointF(2, 2);
//写字符串到图片中
g.DrawString(str, font, brush, point);
//给图片画边框
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//生成一个内存流对象,便于存储并输出图片
MemoryStream ms = new MemoryStream();
//保存绘制的图片到内存流ms中
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//输出二进制图片流
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
}
}
}
登陆页面的验证:
protected void jll_Click(object sender, EventArgs e)
{
string code = Request.Form["check"];
//使用cookies判断
if (code == System.Web.HttpContext.Current.Request.Cookies["code"].Value)
//使用session判断
if (code == Session["code"].ToString())
{
Response.Write("<script>alert(‘right!‘)</script>");
}
else
{
Response.Write("<script>alert(‘false!‘)</script>");
}
}