本程序丰富了以前写的关于登录时随机图片的产生,复制一下代码程序完全可以运行。
主要参考了jeerisguo博客中关于此功能的实现,本人只是做了一些小小的改动。
主要技术是实现了ICallbackEventHandler接口,关于此技术如有不明白请参阅其他相关资料,此处不作讨论。

做个广告:欢迎加入.NET技术群,dotnetbeginner@hotmail.com

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

<!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>
<script  language="javascript" type="text/javascript">
    
var div;
    
    
function callback()
    
{
        
var name=document.getElementById("UserName").value;
        
var pass=document.getElementById("PassWord").value;
        
var checkcode=document.getElementById("CheckCode").value;
        div 
= document.getElementById("show_msg");
        div.innerHTML 
= '正在验证,请稍后..';
        div.style.backgroundColor 
= "AliceBlue";  
        dos(name 
+ "&" + pass + "&" + checkcode);
    }

    
    
function ReceiveServerData(text)
    
{           
        alert(text);
        div.style.display
="none";
        location.href 
= location.href;
    }

    
    
function getRandomNum()
    
{
        
return Math.random();
    }

</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<table style="width: 218px; height: 96px;">
            
<tr>
                
<td style="width: 35px">
                    
<asp:Label ID="Label1" runat="server" Text="UserName" ></asp:Label></td>
                
<td style="width: 205px">
                    
<input id="UserName" type="text" style="border-style:groove; border-color:#A9BAC9; width:148px" /></td>
            
</tr>
            
<tr>
                
<td style="width: 35px; height: 12px;">
                    
<asp:Label ID="Label2" runat="server" Text="PassWord" Width="44px"></asp:Label></td>
                
<td style="width: 205px; height: 12px;">
                    
<input id="PassWord" type="password" style="border-style:groove; border-color:#A9BAC9; width:148px" /></td>
            
</tr>
            
<tr>
                
<td>
                    
<img id="Image1" src="Image.aspx" alt="更改图片" style="cursor:hand" onclick="javascript:document.getElementById('Image1').src = 'Image.aspx?randomNumber='+getRandomNum()" />
                    
</td>
                
<td style="height: 13px; width: 205px;">
                    
<input id="CheckCode" style="border-style:groove; border-color:#A9BAC9; width:148px" type="text" maxlength="6" /></td>
            
</tr>
            
<tr>
                
<td colspan="2">
                
<div id="show_msg"></div>
                
</td>
            
</tr>
            
<tr>
                
<td style="height: 26px">
                
</td>
                
<td style="width: 205px; height: 26px">
                    
<input id="Login" type="button" value="登 陆"  onclick="callback()" style="width: 60px" />
                
</td>
            
</tr>
        
</table>
    
</div>
    
</form>
</body>
</html>

login.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class login : System.Web.UI.Page, ICallbackEventHandler
{
    
/// <summary>
    
/// 存放结果
    
/// </summary>

    private string result;

    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
        
{
            
//获取一个对客户端函数的引用;调用该函数时,将启动一个对服务器端事件的客户端回调。
            string strReference = Page.ClientScript.GetCallbackEventReference(this"text""ReceiveServerData""");
            
//注册客户端方法
            string strCallbackScript = "function dos(text){" + strReference + ";}";
            
//向客户端写入脚本块
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dos", strCallbackScript, true);
        }

    }


    
/// <summary>
    
/// 处理回调事件,这个是接口要实现的方法一
    
/// </summary>
    
/// <param name="pstrInputData">用户输入数据</param>

    public void RaiseCallbackEvent(string pstrInputData)
    
{
        
//从本地Session中获取验证码
        string strValidCode = Session["ValidCode"].ToString();
        
string[] strArrInputData = pstrInputData.Split(new char[] '&' }3);
        
if (strArrInputData[2!= strValidCode)
            result 
= "验证码错误!请重新输入";
        
//这里是验证用户名和密码
        else if (strArrInputData[0== "admin" && strArrInputData[1== "admin")
            result 
= "登录成功";
        
else
            result 
= "登录失败";
    }


    
/// <summary>
    
///  返回回调事件的结果,这个是接口要实现的方法二
    
/// </summary>
    
/// <returns></returns>

    public string GetCallbackResult()
    
{
        
return result;
    }

}

Image.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Image.aspx.cs" Inherits="Image" %>

<!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>

Image.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Image : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        createImage(createRandomCode(
6));
    }


    
/// <summary>
    
/// 创建随机代码
    
/// </summary>
    
/// <param name="piLength"></param>
    
/// <returns></returns>

    private string createRandomCode(int piLength)
    
{
        
//此处仅用中文作为验证字符,也可使用字符数字其他符号
        string strWords = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";
        
char[] chrWord = strWords.ToCharArray();

        System.Text.StringBuilder sbResult 
= new System.Text.StringBuilder();

        
//随机数
        Random rnd = new Random();
        
for (int i = 0; i < piLength; i++)
        
{
            sbResult.Append(chrWord[rnd.Next(chrWord.Length)].ToString());
        }


        
return sbResult.ToString();
    }


    
/// <summary>
    
/// 生成图片
    
/// </summary>
    
/// <param name="pstrCode">用户生成图片的代码</param>

    private void createImage(string pstrCode)
    
{
        
//如果代码为空则结束
        if (string.IsNullOrEmpty(pstrCode.Trim()))
            
return;
        
//将代码放到本地session中,以便用于验证
        Session["ValidCode"= pstrCode;
        
//设置图片大小,根据代码长度来生成
        
//此处也可以使用Image对象
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Convert.ToInt32(pstrCode.Length * 22), 20);
        
//画图对象
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp);
        
//随机数
        Random rnd = new Random();
        
//设置图片为白色
        g.Clear(System.Drawing.Color.White);
        
//画图片的背景噪音线
        for (int i = 0; i < 25; i++)
        
{
            
int x1 = rnd.Next(bmp.Width);
            
int x2 = rnd.Next(bmp.Width);
            
int y1 = rnd.Next(bmp.Height);
            
int y2 = rnd.Next(bmp.Height);
            g.DrawLine(
new System.Drawing.Pen(System.Drawing.Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255)), (float)(rnd.Next(3))), x1, x2, y1, y2);
        }


        System.Drawing.Font fnt 
= new System.Drawing.Font("Arial"12, getFontStyle(rnd.Next(15)));
        System.Drawing.Drawing2D.LinearGradientBrush brsh 
= new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(00, bmp.Width, bmp.Height), System.Drawing.Color.Blue, System.Drawing.Color.Red, 1.2ftrue);
        g.DrawString(pstrCode, fnt, brsh, 
52);

        
//画图片的前景噪音点
        g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255))), 00, bmp.Width - 1, bmp.Height - 1);

        System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType 
= "bmp/Gif";
        Response.BinaryWrite(ms.ToArray());
    }


    
/// <summary>
    
/// 获取FontStyle
    
/// </summary>
    
/// <param name="piFontStyle">1~5之间的一个数字</param>
    
/// <returns></returns>

    private System.Drawing.FontStyle getFontStyle(int piFontStyle)
    
{
        
switch (piFontStyle)
        
{
            
case 1:
                
return System.Drawing.FontStyle.Bold;
            
case 2:
                
return System.Drawing.FontStyle.Italic;
            
case 3:
                
return System.Drawing.FontStyle.Regular;
            
case 4:
                
return System.Drawing.FontStyle.Strikeout;
            
case 5:
                
return System.Drawing.FontStyle.Underline;
            
default:
                
return System.Drawing.FontStyle.Regular;
        }

    }

}
posted on 2007-07-20 13:02  seamanhy  阅读(1338)  评论(0编辑  收藏  举报