最近在开发中遇到要实现登录验证码的功能,在网上借鉴了一下并加以扩展,供大家分享.
代码如下:
///首先新建一个ValidateCode.ashx文件.
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
namespace WebApplication3
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ValidateCode : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);///特别注意,如不加,单击验证图片'看不清换一张',无效果.
this.CreateCheckCodeImage(GenerateCheckCode(context),context);
}
public bool IsReusable
{
get
{
return false;
}
}
private string GenerateCheckCode(HttpContext context)
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 6; i++)
{
number = random.Next();
if (number % 2 == 0)