HtmlHelper of ASP. NET Image Verification code

Source: Internet
Author: User
A picture verification code of the HtmlHelper, the original calling code is as follows:

 <script language= ' javascript ' Type= "Text/javascript" > $ (document). Ready (function () {$ ("#validateCode"). Bind ("click", Function () {var url = $ (thi s). attr ("src"); URL + = "?" + math.random (); $ (this). attr ("src", url); }); }); </script>

After encapsulation into HtmlHelper:
@Html. Validatecode ()
Use the following steps:
1. Build a Verification Code 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"; priva Te 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 Mv  Chtmlstring 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 validatecod E (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 fi Nalid = 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", "Can't you see?") I'll try it! "); 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 RouteValue Dictionary (); if (htmlattributes! = null) {foreach (PropertyDescriptor property in Typedescriptor.getproperties (Htmlattributes)) {res Ult. ADD (property. Name.replace (' _ ', '-'), property. GetValue (htmlattributes)); }} return result; } } }

2. Generate code for CAPTCHA:

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>///maximum length of the verification Code///&LT  ;/summary> public int MaxLength {get {return];}///<summary>///Minimum length of verification code///</summary> public int MinLength {get {return 1;}///<summary>//Generate Verification Code///</summary>//<param name= "Length" > Specify the length of the Verification code Degrees </param>///<returns></returns> public string createvalidatecode (int length) {var randmembers = new I Nt[length]; var validatenums = new Int[length]; var validatenumberstr = ""; Generate starting sequence value 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; }//Generate random numbers for (var i = 0; i < length; i++) {var rand = new Random (Seeks[i]), var pownum = 1 * (int) Math.pow (lengt h); Randmembers[i] = rand. Next (Pownum, Int32.MaxValue); }//extract random numbers 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)); }//Generate Verification code for (var i = 0; i < length; i++) {validatenumberstr + = Validatenums[i]. ToString (); } return VALIDATENUMBERSTR; }///<summary>//Create a picture of the captcha///</summary>//<param name= "Validatecode" > Verification Code </param> public byt E[] Createvalidategraphic (string validatecode) {var image = new Bitmap ((int) math.ceiling (validatecode.length * 12.0), 22 ); var g = graphics.fromimage (image);  try {//Generate random generator var random = new Random ();//empty the picture background color g.clear (color.white);//Draw the image of the interference line for (int i = 0; i <; 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", page, (FontStyle.Bold | Fontstyle.italic)); String[] FontName = {"Chinese new Wei", "Song Body", "round Body", "blackbody", "Official Script"}; var font = new Font (fontname[new Random (). Next (0, Validatecode.length)], A, (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); Picture the foreground interference point for (var i = 0; i < i++) {var x = random. Next (image. Width); var y = random. Next (image. Height); Image. SetPixel (x, Y, Color.FromArgb (random. Next ())); }//Draw the border line of the picture G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1); Save picture Data var stream = new MemoryStream (); Image. Save (stream, imageformat.jpeg); Output picture stream return stream. ToArray (); } finally {g.dispose (); IMage. Dispose (); }}///<summary>///Get the length of the CAPTCHA picture///</summary>//<param name= "Validatenumlength" > The length of the verification code </param& Gt <returns></returns> public static int getimagewidth (int validatenumlength) {return (int) ( Validatenumlength * 12.0); }///<summary>///Get the height of the verification code///</summary>//<returns></returns> public static double Getimageh Eight () {return 23;}} }

3. Build a 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. Let controller inherit 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 () {VIEWBA G.message = "Welcome to ASP. mvc!"; return View (); } public ActionResult about () {var code = Getvalidatecode (); return View ();}} }

5. Page Call Code:

@using MvcApplication1 @{viewbag.title = "About Us",} 

6. Verification Code:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.