ASP. NET MVC5 generates a verification code, asp. netmvc5
1 ValidateCode. cs
Using System; using System. drawing; using System. drawing. drawing2D; using System. drawing. imaging; using System. IO; namespace Common {// <summary> // the class that generates the verification code /// </summary> 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 verification code length </param> /// <returns> </returns> public string CreateValidateCode (int length) {int [] randMembers = new int [length]; int [] validateNums = new int [length]; string validateNumberStr = ""; // generate the Starting sequence value int seekSeek = unchecked (int) DateTime. now. ticks); Random seekRand = new Random (seekSeek); int beginSeek = (int) seekRand. next (0, Int32.MaxValue-length * 10000); int [] seeks = new int [length]; for (int I = 0; I <length; I ++) {beginSeek + = 10000; seeks [I] = beginSeek;} // generates a random number for (int I = 0; I <length; I ++) {Random rand = new Random (seeks [I]); int pownum = 1 * (int) Math. pow (10, length); randMembers [I] = rand. next (pownum, Int32.MaxValue) ;}// extract random numbers for (int I = 0; I <length; I ++) {string numStr = randMembers [I]. toString (); int numLength = numStr. length; Random rand = new Random (); int numPosition = rand. next (0, numLength-1); validateNums [I] = Int32.Parse (numStr. substring (numPosition, 1) ;}// generate the verification code for (int I = 0; I <length; I ++) {validateNumberStr + = validateNums [I]. toString ();} return validateNumberStr ;} /// <summary> /// the image for creating the verification code /// </summary> /// <param name = "containsPage"> the page object to be output </param> /// <param name = "validateNum"> Verification Code </param> public byte [] CreateValidateGraphic (string validateCode) {Bitmap image = new Bitmap (int) Math. ceiling (validateCode. length * 12.0), 22); Graphics g = Graphics. fromImage (image); try {// generate Random generator random Random = new Random (); // clear the image background color g. clear (Color. white); // The interference line of the picture. for (int I = 0; I <25; I ++) {int x1 = random. next (image. width); int x2 = random. next (image. width); int y1 = random. next (image. height); int 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); LinearGradientBrush 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 disturbance of the image to be painted for (int I = 0; I <100; I ++) {int x = random. next (image. width); int y = random. next (image. height); image. setPixel (x, y, Color. fromArgb (random. next ();} // draw the border line g of the image. drawRectangle (new Pen (Color. silver), 0, 0, image. width-1, image. height-1); // Save the image data. MemoryStream = new MemoryStream (); image. save (stream, ImageFormat. jpeg); // return stream of the output image 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> /// height of the Verification Code obtained /// </summary> /// <returns> </returns> public static double GetImageHeight () {return 22.5 ;}}}
2. In Controller. cs, add an Action to save the generated verification code to the Session and output the verification code image.
[AllowAnonymous] public ActionResult GetValidateCode() { ValidateCode vCode = new ValidateCode(); string code = vCode.CreateValidateCode(4); Session["ValidateCode"] = code; byte[] bytes = vCode.CreateValidateGraphic(code); return File(bytes, @"image/jpeg"); }
3 call method: add the label to the page on which the verification code is to be used:
4. Effect
[HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task <ActionResult> Login (LoginViewModel model, string returnUrl) {if (model. ValidCode! = Session ["ValidateCode"]. toString () {ModelState. addModelError ("", "Incorrect verification code. "); return View (model);} if (ModelState. isValid) {var user = await UserManager. findAsync (model. userName, model. password); if (user! = Null) {await SignInAsync (user, model. rememberMe); return RedirectToLocal (returnUrl);} else {ModelState. addModelError ("", "Invalid username or password. ") ;}}// if an error occurs at this step, the return View (model) form is displayed again );}
6. Click the image to refresh the verification code.
@section Scripts { @Scripts.Render("~/bundles/jqueryval")<script type="text/javascript"> $(function () { $("#valiCode").bind("click", function () { this.src = "../Account/GetValidateCode?time=" + (new Date()).getTime(); }); });</script>}
I used HtmlActionLink In the aspnet mvc5 project to generate a link,
Are you setting the correct parameters? The following is a simple example,
@ Html. ActionLink ("Create New", "Create") the first parameter above is the connection text, and "Create" is the specific Action Method. If your Action Method is in another Controller, you need to add another parameter that represents the Controller.
@ Html. ActionLink ("Go to contact page", "Contact", "Home ")