先看这个demo的解决方案图
Entity是实体,里面有验证码的实体
private string contentType = "image/pjpeg"; private ImageFormat imageFormat = ImageFormat.Jpeg; public Bitmap Image { get; set; } public string ContentType { get { return contentType; } set { contentType = value; } } public ImageFormat ImageFormat { get { return imageFormat; } set { imageFormat = value; } }
Plugin是插件
这个验证码是插件机制实现的
接口文件为
public interface IVerifyImage { VerifyImageInfo GenerateImage(string code, int width, int height, Color bgcolor, int textcolor); }
provider类是一个抽象工厂
代码为
private static Hashtable _instance = new Hashtable(); private static object lockHelper = new object(); //通过接口和反射结合配置文件信息来做整站多验证码技术 public static IVerifyImage GetInstance(string assemlyName) { if (!_instance.Contains(assemlyName)) { lock (lockHelper) { if (!_instance.ContainsKey(assemlyName)) { IVerifyImage p = null; try { p = (IVerifyImage)Activator.CreateInstance(Type.GetType(string.Format("Plugin.VerifyImage.{0}.VerifyImage,Plugin.VerifyImage.{0}", assemlyName), false, true)); } catch { p = new Plugin.VerifyImage.JpegImage.VerifyImage(); } _instance.Add(assemlyName, p); } } } return (IVerifyImage)_instance[assemlyName]; }
验证码相关对象是通过发射机制创建的
具体路径信息写在配置文件中
这样可以设置多个验证码类
具体验证码相关代码请下载这个demo自己去研究
做一个页面,重写他的onInit事件,把验证码输出出来
protected override void OnInit(EventArgs e) { base.OnInit(e); string verifyAssembly = "JpegImage";//此处信息可从配置文件获得 string bgColor = "";//Request.QueryString["bgcolor"].Trim(); int fontColor = 1; //StrToInt(Request.QueryString["fontcolor"].Trim(), 1); string[] bgcolorArray = bgColor.Split(','); Color bg = Color.White; if (bgcolorArray.Length == 1 && bgColor != string.Empty) { bg = ToColor(bgColor); } else if (bgcolorArray.Length == 3 && IsNumericArray(bgcolorArray)) { bg = Color.FromArgb(StrToInt(bgcolorArray[0], 255), StrToInt(bgcolorArray[1], 255), StrToInt(bgcolorArray[2], 255)); } VerifyImageInfo verifyimg = Plugin.VerifyImage.VerifyImageProvider.GetInstance(verifyAssembly).GenerateImage(CreateAuthStr(5, false), 120, 60, bg, fontColor); Bitmap image = verifyimg.Image; System.Web.HttpContext.Current.Response.ContentType = verifyimg.ContentType; //MemoryStream ms = new MemoryStream(); image.Save(this.Response.OutputStream, verifyimg.ImageFormat); }
这里涉及到很多工具方法,请下载demo自己研究
调用验证码可以在页面写JS代码
<script type="text/javascript"> document.getElementById('vcodeimg').src='/tools/VerifyImagePage.aspx?id=4&time=' + Math.random(); </script>
源代码下载
vertify.rar