Htmlhelper_ practical skills of ASP.net picture verification code

Source: Internet
Author: User
Tags httpcontext rand static class
A picture verification code HtmlHelper, the original calling code is as follows:
Copy Code code as follows:


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

After encapsulation into HtmlHelper:
@Html. Validatecode ()
Use the following steps:
1. Build a Verification Code helper
Copy Code code as follows:

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)
{
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", "Can't see clearly?") Point I'll try! ");
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. Code to generate verification code:
Copy Code code as follows:

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 verification code
</summary>
public int MaxLength
{
get {return 10;}
}
<summary>
Minimum length of verification code
</summary>
public int MinLength
{
get {return 1;}
}
<summary>
Generate Verification Code
</summary>
<param name= "Length" > Specified verification code lengths </param>
<returns></returns>
public string Createvalidatecode (int length)
{
var randmembers = new Int[length];
var validatenums = new Int[length];
var validatenumberstr = "";
Generate Start Sequence values
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 (length);
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 verification code
</summary>
<param name= "Validatecode" > Verification Code </param>
Public byte[] Createvalidategraphic (string validatecode)
{
var image = new Bitmap ((int) math.ceiling (validatecode.length * 12.0), 22);
var g = graphics.fromimage (image);
Try
{
Generate a random generator
var random = new Random ();
Empty picture background color
G.clear (Color.White);
Disturbing lines for drawing pictures
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", FontStyle.Bold | Fontstyle.italic));
String[] FontName = {"XXFarEastFont-Arial", "Song Body", "round Body", "blackbody", "Official Script"};
var font = new Font (fontname[new Random (). Next (0, Validatecode.length)], (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 of 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 a picture's border line
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 Verification code picture
</summary>
<param name= "Validatenumlength" > Verification Code length </param>
<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 Getimageheight ()
{
return 23;
}
}
}

3. Build a Basecontroller
Copy Code code as follows:

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:
Copy Code code as follows:

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. Page Call Code:
Copy Code code as follows:

@using MvcApplication1
@{
Viewbag.title = "About Us";
}
<p>
Put the content here.
</p>
@Html. Validatecode ()

6. Verification Code Effect chart:

Source can download from here: Validatecode.rar
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.