图片验证代码主要包括两个部分,登陆部分和图片验证码加载部分。
1.登陆前台部分如下:Login.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>用户登录</title>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<link href="Style/cs.css" rel="stylesheet" type="text/css" />
<script src="js/webutil.js" type="text/javascript"></script>
<style type="text/css">
*
{
margin: 0px auto;
padding: 0px;
}
body
{
background: #ffffff url(images/LoginIn/logbg.gif) repeat-x;
width: 100%;
height: 100%;
font: 12px "宋体";
}
.logbg
{
background: url(images/LoginIn/logbg.jpg) no-repeat center;
height: 520px;
width: 1000px;
margin-top: 40px;
}
.log_txt
{
padding-top: 220px;
width: 280px;
}
.text
{
margin-bottom: 12px;
color: #272727;
}
.lottext
{
border: #9a9b9c 1px solid;
width: 200px;
height: 20px;
line-height: 20px;
color: #a3c0e8;
}
.yanzm
{
width: 85px;
border: #9a9b9c 1px solid;
height: 20px;
line-height: 20px;
}
.checkbox
{
margin-left: 40px;
}
.bott
{
clear: both;
margin-top: 0px;
margin-left: 50px;
}
.foonter
{
text-align: center;
color: #262727;
margin-top: 40px;
margin-left: 30px;
line-height: 25px;
}
.jiz
{
color: #262626;
margin-left: 5px;
}
.waji
{
float: left;
margin-left: 10px;
padding-top: 6px;
}
.waji a
{
color: #003b7f;
text-decoration: none;
}
.text
{
margin-top: 10px;
}
.text1
{
margin-top: 10px;
margin-left: 35px;
}
.dis1
{
display: block;
}
.undis1
{
display: none;
}
</style>
<script src="Js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(window).load(function() {
// alert($("#txtMm").val());
// if ($.cookie("GylyUserState") != null) {
// alert(123);
// }
});
</script>
<script type="text/javascript">
function ChangeCode() {
var date = new Date();
var myImg = document.getElementById("ImageCheck");
myImg.src = "ValidateCode.aspx?flag=" + date.getMilliseconds()
return false;
}
function ChangeImg(o) {
if (o.indexOf("#") != -1) {
var imgsrc = o.split("#")[0];
document.getElementById('oImg').src = "images/LoginIn/" + imgsrc;
}
}
function IsNull() {
var a = document.getElementById("txtYh");
if (a.value == "用户登录/邮箱登录") {
document.getElementById("txtYh").value = "";
document.getElementById("txtYh").style.color = "black";
}
}
window.onload = function() {
var a = document.getElementById("txtYh");
if (a.value == "用户登录/邮箱登录") {
document.getElementById("txtYh").style.color = "#a3c0e8";
}
else {
document.getElementById("txtYh").style.color = "black";
}
}
</script>
</head>
<script language="javascript" type="text/javascript">
if (window != top)
top.location.href = location.href;
</script>
<body>
<form id="form1" runat="server">
<div class="logbg">
<div class="log_txt">
<div class="text">
用户名:<asp:TextBox ID="txtYh" runat="server" CssClass="lottext" Style="color: #a3c0e8;"
Text="用户登录/邮箱登录" οnfοcus="IsNull()"></asp:TextBox>
</div>
<div class="text">
密 码:<asp:TextBox ID="txtMm" runat="server" CssClass="lottext" TextMode="Password"
EnableTheming="True"></asp:TextBox>
</div>
<div class="text">
验证码:<asp:TextBox ID="txtYzm" runat="server" CssClass="yanzm"></asp:TextBox>
<span style="margin-left: 0px;"><a id="A2" href="" οnclick="ChangeCode();return false;"
style="height: 21px;">
<asp:Image ID="ImageCheck" runat="server" ImageUrl="ValidateCode.aspx" ImageAlign="AbsMiddle"
ToolTip="看不清,换一个" Height="21px"></asp:Image>
</a></span>
</div>
<div class="checkbox">
<p class="jiz">
<asp:CheckBox ID="RememberUser" runat="server" Text=" 记住登录状态" /></p>
</div>
<div style="color: #e33904; padding-top: 0px; margin-left: 80px;">
<asp:Label ID="lbXxts" runat="server" Width="120px" Height="16px" Style="text-align: center;
padding-top: 0px;"></asp:Label>
</div>
<div>
<p style="float: left;">
<asp:ImageButton ID="btnDL" runat="server" CssClass="bott" ImageUrl="images/LoginIn/bottbg.gif"
OnClick="btnDL_Click" /></p>
<p class="waji">
<a href="FindPassword.aspx">忘记密码?</a></p>
</div>
</div>
<div class="foonter">
<p>
贵阳市生态文明建设委员会</p>
Copyright<span style="font-family: Arial;">©</span>2012 技术支持:北京东方泰坦科技股份有限公司
</div>
</div>
</form>
</body>
</html>
2.登陆后台程序Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otitan.Web.Func;
using Otitan.BLL;
namespace Otitan.Web
{
/// <summary>
/// 功能:用户登录
/// 创建者:阮林佳
/// 创建日期:2012-8-28
/// </summary>
public partial class Login : System.Web.UI.Page
{
BLL.BS_USER b_user = new Otitan.BLL.BS_USER(); //用户表
Model.BS_USER m_user = new Otitan.Model.BS_USER();
//页面加载
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//接受cs系统参数登录系统
string user = Request.QueryString["user"] == null ? "" : Request.QueryString["user"].ToString();
if (user != "")
{
m_user = b_user.GetExtendModel(user);
GetState(m_user);
}
string username = Request.QueryString["username"];
string password = Request.QueryString["password"];
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
CheckState(username, password);
return;
}
ReadCookie();
}
}
/// <summary>
/// 读取Cookie,获取登录信息
/// </summary>
private void ReadCookie()
{
//读取cookie
HttpCookie aCookie = Request.Cookies["GylyUserState"];
if (aCookie != null)
{
if (aCookie.Values["UserCode"] != null && aCookie.Values["UserCode"].ToString() != "")
{
txtYh.Text = aCookie.Values["UserCode"].ToString();
}
//txtMm.Text = Otitan.Common.DEncrypt.DESEncrypt.Decrypt(aCookie.Values["PassWord"].ToString());
//if (aCookie.Values["PassWord"] != null && aCookie.Values["PassWord"].ToString() != "")
//{
// txtMm.Attributes.Add("Value", Otitan.Common.DEncrypt.DESEncrypt.Decrypt(aCookie.Values["PassWord"].ToString()));
// txtMm.Attributes.Add("OnFocus", "this.value=''");
//}
}
}
/// <summary>
/// cs到bs判断是否可以登录
/// </summary>
/// <param name="p_username">用户名</param>
/// <param name="p_password">加密后的密码</param>
protected void CheckState(string p_username, string p_password)
{
Otitan.BLL.BS_USER b_user = new BS_USER();
Otitan.Model.BS_USER m_user = b_user.GetExtendModel(p_username);
if (m_user != null)
{
if (m_user.PASSWORD == p_password)
{
UserState userstate = new UserState();
userstate.M_User = m_user;
Session.Add("UserState", userstate);
Response.Redirect("SystemSelect.aspx");
}
}
}
protected void btnDL_Click(object sender, ImageClickEventArgs e)
{
Model.BS_USER m_user;
string usercode = txtYh.Text.Trim();
if (txtYh.Text != "用户登录/邮箱登录")
{
if (usercode == "")
{
lbXxts.Text = "用户名不能为空";
txtYzm.Text = "";
return;
}
if (txtYzm.Text.Trim() == "")
{
lbXxts.Text = "验证码不能为空";
return;
}
if (Session["CheckCode"] == null || txtYzm.Text.ToLower() != Session["CheckCode"].ToString().ToLower())
{
lbXxts.Text = "验证码不正确";
txtYzm.Text = "";
return;
}
string userpwd = txtMm.Text;
m_user = b_user.GetExtendModel(usercode);
if (m_user == null)
{
lbXxts.Text = "用户名不存在";
txtYzm.Text = "";
return;
}
if (m_user.ISACTIVE == 0)
{
lbXxts.Text = "用户未激活";
txtYzm.Text = "";
return;
}
//string mn = Otitan.Common.DEncrypt.DESEncrypt.Decrypt(m_user.PASSWORD);
if (m_user.PASSWORD != Otitan.Common.DEncrypt.DESEncrypt.Encrypt(txtMm.Text))
{
lbXxts.Text = "密码不正确";
txtYzm.Text = "";
return;
}
if (txtYh.Text == "用户登录/邮箱登录")
{
usercode = "gys_admin";
}
else
{
usercode = txtYh.Text;
}
m_user = b_user.GetExtendModel(usercode);
}
else
{
m_user = b_user.GetExtendModel("gys_admin");
}
GetState(m_user);
}
protected void GetState(Model.BS_USER m_user)
{
if (m_user != null)
{
string usercode = txtYh.Text.Trim();
UserState userstate = new UserState();
userstate.M_User = m_user;
Session.Add("UserState", userstate);
if (RememberUser.Checked)
{
HttpCookie cookie = new HttpCookie("GylyUserState");
cookie.Values.Add("UserCode", usercode);
// cookie.Values.Add("PassWord", m_user.PASSWORD);
cookie.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(cookie);
}
Response.Redirect("SystemSelect.aspx");
}
else
{
lbXxts.Text = "用户密码不匹配";
}
}
}
}
3.图片加载程序ValidateCode.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
namespace Otitan.Web
{
/// <summary>
///
/// </summary>
public partial class ValidateCode : System.Web.UI.Page
{
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
string checkCode = GetRandomCode(4);
Session["CheckCode"] = checkCode;
SetPageNoCache();
CreateImage(checkCode);
}
/// <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>
///
/// </summary>
/// <param name="codeCount"></param>
/// <returns></returns>
private string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
return CreateRandomCode(codeCount);//性能问题
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
/// <summary>
///
/// </summary>
/// <param name="CodeCount"></param>
/// <returns></returns>
private string GetRandomCode(int CodeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(33);
while (temp == t)
{
t = rand.Next(33);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
/// <summary>
///
/// </summary>
/// <param name="checkCode"></param>
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 14);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(Color.Black);
Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
// g.Clear(Color.AliceBlue);//背景色
g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色
char[] ch = checkCode.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] >= '0' && ch[i] <= '9')
{
//数字用红色显示
g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
}
else
{ //字母用黑色显示
g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
}
}
//for循环用来生成一些随机的水平线
// Pen blackPen = new Pen(Color.Black, 0);
// Random rand = new Random();
// for (int i=0;i<5;i++)
// {
// int y = rand.Next(image.Height);
// g.DrawLine(blackPen,0,y,image.Width,y);
// }
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//history back 不重复
Response.Cache.SetNoStore();//这一句
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
}
}