index.aspx.cs:
//需要在index.aspx代码中指定 img src = "PassEx.aspx"
//为防止缓存也可以为img src = "PassEx.aspx?requestid=随机数"
private void Button1_Click(object sender, System.EventArgs e)
{
if(Page.IsValid)
{
if(TextBox3.Text.Trim().Equals(Session["CheckPasswd"].ToString().Trim()))
{
if(TextBox1.Text.Trim().Equals("zk") && TextBox2.Text.Trim().Equals("123"))
{
Response.Write("登陆成功!!!");
Response.End();
}
else
{
TextBox1.Text = "";
TextBox2.Text = "";
this.AlertMessageBox("用户名或密码错误");
}
}
else
{
TextBox3.Text = "";
this.AlertMessageBox("附加码错误");
}
}
}
private void AlertMessageBox(string msg)
{
Response.Write("<script>alert('" + msg + "');</script>");
}
============================================================
PassEx.aspx.cs
public class WebForm1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
Session["CheckPasswd"] = new Random(unchecked((int)System.DateTime.Now.Ticks)).Next().ToString().Substring(2,4);
Response.ClearContent();
Response.ContentType = "image/GIF";
Response.BinaryWrite(CreateImage(Server,20,53));
}
}
private byte[] CreateImage(System.Web.HttpServerUtility Server,int Height, int Width)
{
try
{
Bitmap pic = new Bitmap(Width,Height,PixelFormat.Format32bppRgb);
Graphics g = Graphics.FromImage(pic);
Rectangle r = new Rectangle(0,0,Width,Height);
g.FillRectangle(new SolidBrush(Color.Silver),r);
g.DrawString(Session["CheckPasswd"].ToString(),new Font("Arial",14),new SolidBrush(Color.Red),2,0);
MemoryStream mStream = new MemoryStream();
pic.Save(mStream,ImageFormat.Gif);
g.Dispose();
pic.Dispose();
return mStream.ToArray();
}
catch
{
return null;
}
}