Create an ashx File
Using system;
Using system. drawing;
Using system. Drawing. imaging;
Using system. text;
Using system. Web;
Using system. Web. sessionstate;
Namespace validatecode
{
/// <Summary>
/// Summary description for $ codebehindclassname $
/// </Summary>
Public class imagecode: ihttphandler, irequiressessionstate
{
Public void processrequest (httpcontext context)
{
Context. response. contenttype = "image/GIF ";
// Create a bitmap object and draw
Bitmap basemap = new Bitmap (200, 60 );
Graphics graph = graphics. fromimage (basemap );
Graph. fillrectangle (New solidbrush (color. White), 0, 0,200, 60 );
Font font = new font (fontfamily. genericserif, 48, fontstyle. Bold, graphicsunit. pixel );
Random r = new random ();
String letters = "abcdefghijklmnpqrstuvwxyz ";
String letter;
Stringbuilder S = new stringbuilder ();
// Add random five letters
For (INT x = 0; x <5; X ++)
{
Letter = letters. substring (R. Next (0, letters. Length-1), 1 );
S. append (letter );
Graph. drawstring (letter, Font, new solidbrush (color. Black), x * 38, R. Next (0, 15 ));
}
// Obfuscation background
Pen linepen = new pen (New solidbrush (color. Black), 2 );
For (INT x = 0; x <6; X ++)
Graph. drawline (linepen, new point (R. next (1, 0,199), R. next (0, 59), new point (R. next (1, 0,199), R. next (0, 59 )));
// Save the image to the output stream
Basemap. Save (context. response. outputstream, imageformat. GIF );
Context. session ["checkcode"] = S. tostring (); // If the irequiressessionstate is not implemented, an error occurs and an image cannot be generated.
Context. response. End ();
}
Public bool isreusable
{
Get {return true ;}
}
}
}
Usage: On the ASPX page
<Asp: textbox id = "txtvalidate" runat = "server"> </ASP: textbox>
<Asp: linkbutton id = "linkbutton1" runat = "server" onclick = "linkbutton1_click"> change one </ASP: linkbutton>
. CS
protected void btnValidate_Click(object sender, EventArgs e)
{
string imageCode = Session["CheckCode"].ToString();
string script = string.Empty;
if (this.txtValidate.Text.Trim().ToUpper() == imageCode)
{
script = "alert('successful');";
}
else
{
script = "alert('fail');";
}
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "alert", script, true);
}