您好,欢迎访问一九零五行业门户网

asp.net 图片验证码的HtmlHelper

一个图片验证码的htmlhelper,原来的调用代码如下:
<img id="validatecode" mailto:src='@url.action(%22getvalidatecode%22)'/> <script language="javascript" type="text/javascript"> $(document).ready(function () { $("#validatecode").bind("click", function () { var url = $(this).attr("src"); url += "?" + math.random(); $(this).attr("src", url); }); }); </script>
封装成htmlhelper后:
@html.validatecode()
使用步骤如下:
1.建一个验证码helper
using system; using system.collections.generic; using system.componentmodel; using system; using system.collections.generic; using system.diagnostics.codeanalysis; using system.globalization; using system.linq.expressions; using system.security.policy; using system.text; using system.web; using system.web.mvc; using system.web.mvc.resources; using system.web.routing; namespace mvcapplication1 { public static class validatecodehelper { private const string idprefix = "validatecode"; private const int length = 4; public static mvchtmlstring validatecode(this htmlhelper helper) { return validatecode(helper, idprefix); } public static mvchtmlstring validatecode(this htmlhelper helper,string id) { return validatecode(helper, id, length); } public static mvchtmlstring validatecode(this htmlhelper helper, string id, int length) { return validatecode(helper, id, length, null); } public static mvchtmlstring validatecode(this htmlhelper helper, string id, object htmlattributes) { return validatecode(helper, id, length, htmlattributes); } public static mvchtmlstring validatecode(this htmlhelper helper, int length, object htmlattributes) { return validatecode(helper, idprefix, length, htmlattributes); } public static mvchtmlstring validatecode(this htmlhelper helper, object htmlattributes) { return validatecode(helper, 4, htmlattributes); } public static mvchtmlstring validatecode(this htmlhelper helper, int length) { return validatecode(helper,length, null); } public static mvchtmlstring validatecode(this htmlhelper helper,string id,int length,object htmlattributes) { string finalid = id + "_imgvalidatecode"; var tagbuild = new tagbuilder("img"); tagbuild.generateid(finalid); var defaultcontroller = ((route)routetable.routes["default"]).defaults["controller"] + "/"; var controller = httpcontext.current.request.url.segments.length == 1 ? defaultcontroller : httpcontext.current.request.url.segments[1]; tagbuild.mergeattribute("src", string.format("/{0}getvalidatecode?length={1}",controller,length)); tagbuild.mergeattribute("alt", "看不清?点我试试看!"); tagbuild.mergeattribute("style","cursor:pointer;"); tagbuild.mergeattributes(anonymousobjecttohtmlattributes(htmlattributes)); var sb = new stringbuilder(); sb.append("<script language=\"javascript\" type=\"text/javascript\">"); sb.append("$(document).ready(function () {"); sb.appendformat("$(\"#{0}\").bind(\"click\", function () {{", finalid); //sb.append("$(this).attr(\"style\", \"cursor:pointer;\");"); sb.append("var url = $(this).attr(\"src\");"); sb.append("url += \"&\" + math.random();"); sb.append("$(this).attr(\"src\", url);"); sb.append("});"); sb.append("});"); sb.append("</script>"); return mvchtmlstring.create(tagbuild+sb.tostring()); } public static routevaluedictionary anonymousobjecttohtmlattributes(object htmlattributes) { var result = new routevaluedictionary(); if (htmlattributes != null) { foreach (propertydescriptor property in typedescriptor.getproperties(htmlattributes)) { result.add(property.name.replace('_', '-'), property.getvalue(htmlattributes)); } } return result; } } }
2.生成验证码的代码:
using system; using system.collections.generic; using system.linq; using system.web; using system.drawing; using system.drawing.drawing2d; using system.io; using system.drawing.imaging; namespace mvcapplication1 { public class validatecode { public validatecode() { } /// <summary> /// 验证码的最大长度 /// </summary> public int maxlength { get { return 10; } } /// <summary> /// 验证码的最小长度 /// </summary> public int minlength { get { return 1; } } /// <summary> /// 生成验证码 /// </summary> /// <param name="length">指定验证码的长度</param> /// <returns></returns> public string createvalidatecode(int length) { var randmembers = new int[length]; var validatenums = new int[length]; var validatenumberstr = ""; //生成起始序列值 var seekseek = unchecked((int)datetime.now.ticks); var seekrand = new random(seekseek); var beginseek = (int)seekrand.next(0, int32.maxvalue - length * 10000); var seeks = new int[length]; for (var i = 0; i < length; i++) { beginseek += 10000; seeks[i] = beginseek; } //生成随机数字 for (var i = 0; i < length; i++) { var rand = new random(seeks[i]); var pownum = 1 * (int)math.pow(10, length); randmembers[i] = rand.next(pownum, int32.maxvalue); } //抽取随机数字 for (var i = 0; i < length; i++) { var numstr = randmembers[i].tostring(); var numlength = numstr.length; var rand = new random(); var numposition = rand.next(0, numlength - 1); validatenums[i] = int32.parse(numstr.substring(numposition, 1)); } //生成验证码 for (var i = 0; i < length; i++) { validatenumberstr += validatenums[i].tostring(); } return validatenumberstr; } /// <summary> /// 创建验证码的图片 /// </summary> /// <param name="validatecode">验证码</param> public byte[] createvalidategraphic(string validatecode) { var image = new bitmap((int)math.ceiling(validatecode.length * 12.0), 22); var g = graphics.fromimage(image); try { //生成随机生成器 var random = new random(); //清空图片背景色 g.clear(color.white); //画图片的干扰线 for (int i = 0; i < 25; i++) { var x1 = random.next(image.width); var x2 = random.next(image.width); var y1 = random.next(image.height); var y2 = random.next(image.height); g.drawline(new pen(color.silver), x1, y1, x2, y2); } //font font = new font("arial", 12, (fontstyle.bold | fontstyle.italic)); string[] fontname = { "华文新魏", "宋体", "圆体", "黑体", "隶书" }; var font = new font(fontname[new random().next(0, validatecode.length)], 12, (fontstyle.bold | fontstyle.italic)); var brush = new lineargradientbrush(new rectangle(0, 0, image.width, image.height), color.blue, color.darkred, 1.2f, true); g.drawstring(validatecode, font, brush, 3, 2); //画图片的前景干扰点 for (var i = 0; i < 100; i++) { var x = random.next(image.width); var y = random.next(image.height); image.setpixel(x, y, color.fromargb(random.next())); } //画图片的边框线 g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1); //保存图片数据 var stream = new memorystream(); image.save(stream, imageformat.jpeg); //输出图片流 return stream.toarray(); } finally { g.dispose(); image.dispose(); } } /// <summary> /// 得到验证码图片的长度 /// </summary> /// <param name="validatenumlength">验证码的长度</param> /// <returns></returns> public static int getimagewidth(int validatenumlength) { return (int)(validatenumlength * 12.0); } /// <summary> /// 得到验证码的高度 /// </summary> /// <returns></returns> public static double getimageheight() { return 23; } } }
3.建一个basecontroller
using system; using system.collections.generic; using system.linq; using system.web; using system.web.mvc; namespace mvcapplication1 { public class basecontroller:controller { public actionresult getvalidatecode(int length) { var vcode = new validatecode(); var code = vcode.createvalidatecode(length); session["validatecode"] = code; var bytes = vcode.createvalidategraphic(code); return file(bytes, @"image/gif"); } protected string getvalidatecode() { return session["validatecode"].tostring(); } } }
4.让controller继承basecontroller:
using system; using system.collections.generic; using system.linq; using system.web; using system.web.mvc; using system.web.security; namespace mvcapplication1.controllers { public class homecontroller :basecontroller { public actionresult index() { viewbag.message = "welcome to asp.net mvc!"; return view(); } public actionresult about() { var code = getvalidatecode(); return view(); } } }
5.页面调用代码:
@using mvcapplication1 @{ viewbag.title = "about us"; } <h2>about</h2> <p> put content here. </p> @html.validatecode()
6.验证码的效果图:
更多asp.net 图片验证码的htmlhelper。
其它类似信息

推荐信息