HtmlHelper of asp.net image Verification Code

Source: Internet
Author: User

HtmlHelper of an image verification code. The original call code is as follows: Copy codeThe Code is 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>

Encapsulated as HtmlHelper:
@ Html. ValidateCode ()
The procedure is as follows:
1. Create a verification code HelperCopy codeThe Code is 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 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
? Defacontroller Controller
: HttpContext. Current. Request. Url. Segments [1];
TagBuild. MergeAttribute ("src", string. Format ("/{0} GetValidateCode? Length = {1} ", controller, length ));
TagBuild. MergeAttribute ("alt", "cannot see clearly? Click here to 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 RouteValueDictionary ();
If (htmlAttributes! = Null)
{
Foreach (PropertyDescriptor property in TypeDescriptor. GetProperties (htmlAttributes ))
{
Result. Add (property. Name. Replace ('_', '-'), property. GetValue (htmlAttributes ));
}
}
Return result;
}
}
}

2. Code for generating the verification code:Copy codeThe Code is 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 the Verification Code
/// </Summary>
Public int MaxLength
{
Get {return 10 ;}
}
/// <Summary>
/// Minimum length of the Verification Code
/// </Summary>
Public int MinLength
{
Get {return 1 ;}
}
/// <Summary>
/// Generate the verification code
/// </Summary>
/// <Param name = "length"> specify the length of the Verification Code </param>
/// <Returns> </returns>
Public string CreateValidateCode (int length)
{
Var randMembers = new int [length];
Var validateNums = new int [length];
Var validateNumberStr = "";
// Generate the 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 (10, 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 the verification code
For (var I = 0; I <length; I ++)
{
ValidateNumberStr + = validateNums [I]. ToString ();
}
Return validateNumberStr;
}
/// <Summary>
/// Image 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 ();
// Clear the background color of the image
G. Clear (Color. White );
// Picture interference line
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 );
// Foreground interference points
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 ()));
}
// Draw the border line of the image
G. DrawRectangle (new Pen (Color. Silver), 0, 0, image. Width-1, image. Height-1 );
// Save image data
Var stream = new MemoryStream ();
Image. Save (stream, ImageFormat. Jpeg );
// Output the image stream
Return stream. ToArray ();
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}
/// <Summary>
/// Obtain the length of the Verification Code Image
/// </Summary>
/// <Param name = "validateNumLength"> Verification code length </param>
/// <Returns> </returns>
Public static int GetImageWidth (int validateNumLength)
{
Return (int) (validateNumLength * 12.0 );
}
/// <Summary>
/// Obtain the height of the Verification Code
/// </Summary>
/// <Returns> </returns>
Public static double GetImageHeight ()
{
Return 23;
}
}
}

3. Create a BaseControllerCopy codeThe Code is 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 the Controller inherit the BaseController:Copy codeThe Code is 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 codeThe Code is as follows: @ using MvcApplication1
@{
ViewBag. Title = "About Us ";
}
<H2> About <P>
Put content here.
</P>
@ Html. ValidateCode ()

6. Verification Code:

Source code can be downloaded 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.