制作验证码主要是利用了C#的GDI绘制,效果如下图所示:
html代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<title>验证码</title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</head>
<body>
<form role="form" onsubmit="return login()" style="margin:100px 100px;">
<div class="form-group">
<input id="userName" class="form-control" style="width:300px;" placeholder="用户名" />
</div>
<div class="form-group">
<input id="userPass" class="form-control" style="width:300px;" placeholder="密码" />
</div>
<div class="form-group form-inline">
<input id="userCode" class="form-control" style="width:220px;" placeholder="验证码" />
<img title="看不清?" class="img-thumbnail" style="cursor:pointer;vertical-align:middle;margin-left:5px;border:none;" src="ashx/CreateValidateCodeHandler.ashx" onclick="this.src = 'ashx/CreateValidateCodeHandler.ashx?_=' + Math.random()" />
</div>
<div>
<input type="submit" class="btn btn-primary" style="width:300px;" value="登录" />
</div>
</form>
<script>
function login() {
var userName = document.getElementById('userName').value;
if (userName === '' || userName === undefined) {
alert('请输入用户名');
return false;
}
var userPass = document.getElementById('userPass').value;
if (userPass === '' || userPass === undefined) {
alert('请输入密码');
return false;
}
var userCode = document.getElementById('userCode').value;
if (userCode === '' || userCode === undefined) {
alert('请输入验证码');
return false;
}
$.ajax({
url: 'ashx/LoginHandler.ashx',
type: 'post',
dataType: 'json',
data: {
userName: userName,
userPass: userPass,
userCode: userCode
},
success: function (data) {
if (data == 'Yes') {
window.location.href = 'index.html';
}
else {
alert('登陆失败');
}
}
})
return false;
}
</script>
</body>
</html>
CreateValidateCodeHandler.ashx代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace WebApplication1.ashx
{
/// <summary>
/// CreateValidateCodeHandler 的摘要说明
/// </summary>
public class CreateValidateCodeHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
string code = GetRandomNumber();
context.Session["code"] = code;
using (Bitmap bitmap = CreateImage(code))
{
bitmap.Save(context.Response.OutputStream, ImageFormat.Bmp);
}
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 随机数字
/// </summary>
/// <returns></returns>
private string GetRandomNumber()
{
string code = string.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
code += random.Next(10);
}
return code;
}
/// <summary>
/// 随机字符
/// </summary>
/// <returns></returns>
private string GetRandomLetter()
{
string code = string.Empty;
Random random = new Random();
for (int i = 0; i < 4; i++)
{
char letter = (char)random.Next(65, 90);
code += letter.ToString();
}
return code;
}
/// <summary>
/// 画图片的背景图+干扰线
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
private Bitmap CreateImage(string code)
{
Bitmap bitmap = new Bitmap(code.Length * 18, 33);
Graphics g = Graphics.FromImage(bitmap);
g.Clear(Color.White);
// 随机颜色、字体
Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.DarkCyan, Color.Purple };
string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
// 绘制背景线
Random random = new Random();
Pen pen = new Pen(Color.LightGray, 1);
for (int i = 0; i < 20; i++)
{
int x1 = random.Next(bitmap.Width);
int x2 = random.Next(bitmap.Width);
int y1 = random.Next(bitmap.Height);
int y2 = random.Next(bitmap.Height);
g.DrawLine(pen, x1, y1, x2, y2);
}
// 绘制字符
for (int i = 0; i < code.Length; i++)
{
Font font = new Font(fonts[random.Next(5)], 15, FontStyle.Bold);
Brush brush = new SolidBrush(colors[random.Next(7)]);
g.DrawString(code[i].ToString(), font, brush, 3 + (i * 15), 2);
}
return bitmap;
}
}
}
LoginHandler.ashx代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Newtonsoft.Json;
namespace WebApplication1.ashx
{
/// <summary>
/// LoginHandler 的摘要说明
/// </summary>
public class LoginHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string userName = context.Request["userName"].ToString();
string userPass = context.Request["userPass"].ToString();
string userCode = context.Request["userCode"].ToString();
if (userName == "admin" && userPass == "123456" && userCode == context.Session["code"].ToString())
{
context.Response.Write(JsonConvert.SerializeObject("Yes"));
}
else
{
context.Response.Write(JsonConvert.SerializeObject("No"));
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}