asp.net验证码

先建立一个asp.net页面ValidateCode.aspx

不写任何东西 :

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

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

 

 

在页面的后台ValidateCode.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.Drawing.Imaging;

namespace RRBManage
{
public partial class VerifyCode : System.Web.UI.Page
{
static string[] FontItems = new string[] { "Arial", "隶书","华文行楷","Helvetica", "宋体","楷书","篆书","燕书","黑体","行书","仿宋",
"Geneva",
"sans-serif",
"Verdana"
};
static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab,
Brushes.ForestGreen,
Brushes.DarkCyan,
Brushes.LightSlateGray,
Brushes.RoyalBlue,
Brushes.SlateBlue,
Brushes.DarkViolet,
Brushes.MediumVioletRed,
Brushes.IndianRed,
Brushes.Firebrick,
Brushes.Chocolate,
Brushes.Peru,
Brushes.Goldenrod
};
static string[] BrushName = new string[] { "OliveDrab",
"ForestGreen",
"DarkCyan",
"LightSlateGray",
"RoyalBlue",
"SlateBlue",
"DarkViolet",
"MediumVioletRed",
"IndianRed",
"Firebrick",
"Chocolate",
"Peru",
"Goldenrod"
};
private static Color BackColor = Color.White;
private static Pen BorderColor = Pens.DarkGray;
private static int Width = 52;
private static int Height = 21;
private Random _random;
private string _code;
private int _brushNameIndex;
override protected void OnInit(EventArgs e)
{

//CODEGEN: This call is required by the ASP.NET Web Form Designer.

//InitializeComponent();
//base.OnInit(e);
}
/**/
/**/
/**/
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//this.Load += new System.EventHandler(this.Page_Load);
}
/**/
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
//
// TODO : initialize
//
this._random = new Random();
this._code = GetRandomCode();
//
// TODO : use Session["code"] save the VerifyCode
//
// Session["code"] = this._code;
HttpCookie cokie = new HttpCookie("RRBCode");
cokie.Value = this._code;
cokie.Expires = DateTime.Now.AddMinutes(10);
HttpContext.Current.Response.Cookies.Add(cokie);
//
// TODO : output Image
//
this.SetPageNoCache();
this.OnPaint();
}
}
/**/
/**/
/**/
/// <summary>
/// 设置页面不被缓存
/// </summary>
private void SetPageNoCache()
{
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
}
/**/
/**/
/**/
/// <summary>
/// 取得一个 4 位的随机码
/// </summary>
/// <returns></returns>
private string GetRandomCode()
{
return Guid.NewGuid().ToString().Substring(0, 4).Replace("0", "a");
}
/**/
/**/
/**/
/// <summary>
/// 随机取一个字体
/// </summary>
/// <returns></returns>
private Font GetFont()
{
int fontIndex = _random.Next(0, FontItems.Length);
FontStyle fontStyle = GetFontStyle(_random.Next(0, 60));
return new Font(FontItems[fontIndex], 12, fontStyle);
}
/**/
/**/
/**/
/// <summary>
/// 取一个字体的样式
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private FontStyle GetFontStyle(int index)
{
switch (index)
{
case 0:
return FontStyle.Bold;
case 1:
return FontStyle.Italic;
default:
return FontStyle.Regular;
}
}
/**/
/**/
/**/
/// <summary>
/// 随机取一个笔刷
/// </summary>
/// <returns></returns>
private Brush GetBrush()
{
int brushIndex = _random.Next(0, BrushItems.Length);
_brushNameIndex = brushIndex;
return BrushItems[brushIndex];
}
/**/
/**/
/**/
/// <summary>
/// 绘画事件
/// </summary>
private void OnPaint()
{
Bitmap objBitmap = null;
Graphics g = null;
try
{
objBitmap = new Bitmap(Width, Height);
g = Graphics.FromImage(objBitmap);
Paint_Background(g);
Paint_Text(g);
// Paint_TextStain(objBitmap);
Paint_Border(g);
Paint_TextStain(objBitmap);
objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
Response.ContentType = "image/gif";
}
catch { }
finally
{
if (null != objBitmap)
objBitmap.Dispose();
if (null != g)
g.Dispose();
}
}
/**/
/**/
/**/
/// <summary>
/// 绘画背景颜色
/// </summary>
/// <param name="g"></param>
private void Paint_Background(Graphics g)
{
g.Clear(BackColor);
}
/**/
/**/
/**/
/// <summary>
/// 绘画边框
/// </summary>
/// <param name="g"></param>
private void Paint_Border(Graphics g)
{
g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);

}
/**/
/**/
/**/
/// <summary>
/// 绘画文字
/// </summary>
/// <param name="g"></param>
private void Paint_Text(Graphics g)
{
g.DrawString(_code, GetFont(), GetBrush(), 3, 1);
}
/**/
/**/
/**/
/// <summary>
/// 绘画文字噪音点
/// </summary>
/// <param name="g"></param>
private void Paint_TextStain(Bitmap b)
{
for (int n = 0; n < 30; n++)
{
int x = _random.Next(Width);
int y = _random.Next(Height);
b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));
}
}
}
}

要调用该验证码的页面login.asp写代码如下:

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

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>人人保后台登录</title>
<link href="css/admin.css" type="text/css" rel="stylesheet">
</head>
<script src="http://localhost:57692/js/jquery.js"></script>
<script type="text/javascript">
//添加管理员验证
function checkAdminLoginInput() {
var name = document.getElementById("txtUserName").value;
var pass = document.getElementById("txtPassWord").value;
var Yzm = document.getElementById("txtYzm").value;
if (name.length == 0 || pass.length < 6 || Yzm.length == 0) {
alert('各项不能为空!');
return false;
}
}
function changeImage() {
//单击触发图片重载事件,完成图片验证码的更换
document.getElementById("imgRandom").src = document.getElementById("imgRandom").src + '?';
}

</script>
<body>
<div class="dengl">
<form id="form1" runat="server">

<div class="dltiao">
<div class="dltiao1">
<img src="images/log1_03.jpg" />
</div>
<div class="dltiao2">
<p>人人保后台系统</p>
<b>THE BACKGROUND SYSTEM </b>
</div>
</div>
<div class="dlkuang">
<div class="dlkuang1">LOGIN</div>
<div class="dlkuang2">
<span>账&nbsp;&nbsp;&nbsp;&nbsp;号</span>
<asp:TextBox ID="txtUserName" runat="server" TabIndex="1" Width="230"></asp:TextBox>
</div>
<div class="dlkuang3">
<span>密&nbsp;&nbsp;&nbsp;&nbsp;码</span>
<asp:TextBox ID="txtPassWord" runat="server" TextMode="Password" Width="230"></asp:TextBox>
</div>
<div class="dlkuang4" >
<span>验证码</span>
<asp:TextBox ID="txtYzm" runat="server" CssClass="yz" Width="132" ></asp:TextBox><img class="l_yzm"
src="/VerifyCode.aspx" height="36" width="97" id="imgRandom" onclick="changeImage()" />
<p class="dl_an">
</div>
<div class="dlkuang5">
<span>
<%=ViewState["errorInfo"] %></span>
<asp:Button ID="Button1" runat="server" Text="立即登录" Width="230"
OnClientClick="return checkAdminLoginInput()" OnClick="Button1_Click" />
</div>
</div>
</form>
</div>
</body>
</html>

 调用验证码的页面的后台login.csde 的代码如下:

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

namespace RRBManage
{

protected void Button1_Click(object sender, EventArgs e)
{
string name = this.txtUserName.Text.Trim();
string pass = this.txtPassWord.Text.Trim();
string yzm = this.txtYzm.Text.Trim();
HttpCookie cokie = Request.Cookies["RRBCode"];
string code = cokie.Value;

if(name.Length == 0 || pass.Length == 0||yzm.Length==0)
{
Jscript.Alert("各项不能为空");
return ;
}
if (code.ToString()!= yzm)
{
ViewState["errorInfo"] = "验证码有误!";
return;}

else
{
Jscript.AlertAndRedirect("无此账号或已被停用,请联系超级管理员!",this.Request.RawUrl);
}
}

}

 

posted @ 2015-08-25 11:55  馒头什么的最喜欢了  阅读(169)  评论(0编辑  收藏  举报