When creating a logon page, we usually need to set a verification code to prevent unauthorized users from logging on illegally by other means. When creating a page verification code, we need to first create an active web page to randomly generate numbers and letters, and store the generated numbers in the session, passed to the logon page for verification. Define a canvas, and draw the background color of the verification code on the active page.CodeAs follows:
Protected void page_load (Object sender, eventargs e) {// display the verification code this. genimg (this. gencode (4); Session ["image"] = This. gencode (4); server. transfer ("default. aspx "); // console. writeline (this. gencode (4);} private string gencode (INT num) {string [] source = {"0", "1", "2", "3 ", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D ", "E", "F", "g", "H", "I", "J", "k", "L", "M", "n ", "O", "P,", "Q", "r", "S", "T", "U", "V", "W ", "X", "Y", "Z"}; string code = ""; // create a random class instance named Random RD = new random (); // obtain the verification code for (INT I = 0; I <num; I ++) {code + = source [Rd. next (0, source. length)];} // return the generated Verification Code return;} // generate the image private void genimg (string code) {// define a canvas bitmap mypalette = new Bitmap (60, 20); // The drawing instance graphics GH = graphics defined on the drawing board. fromimage (mypalette); // define a rectangle rc = new rectangle (0, 0, 60, 20); // fill the rectangle GH. fillrectangle (New solidbrush (color. blue), RC); // draw the GH string in the rectangle. drawstring (Code, new font ("", 16), new solidbrush (color. white), RC); // display the image mypalette. save (response. outputstream, imageformat. JPEG); GH. dispose (); mypalette. dispose ();}
After the verification code is generated randomly on the active page, we need to receive it on the logon page. The generated verification code is displayed as follows:
Protected void page_load (Object sender, eventargs e) {// set the imageurl attribute of the btnimage control to the Verification code page this. imagebutton1.imageurl = "active. aspx ";} protected void button#click (Object sender, eventargs e) {string code = session [" image "]. tostring (). trim (); // console. writeline (CODE); string txtbox = This. textbox3.text. tostring (). trim (); If (code = txtbox. toupper () {response. redirect ("result. aspx ");} else respons E. Write ("<script language = 'javascript '> alert ('jump failed! '); </SCRIPT> ");}
At this point, the entire process of dynamically generating verification codes is completed and the verification code is completed.