我想實現這個Captcha並且由於它沒有一個選項來生成一個新的形象,我試圖建立一個與我這樣做:.aspx的只有加載1次
private Panel buildCaptchaElement(XmlNode node)
{
Panel p1 = new Panel();
Label l = new Label();
l.Text = node.ChildNodes[3].InnerText;
TextBox tb = new TextBox();
tb.ID = "Captcha_Tb";
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ID = "Captcha_Img";
img.ImageUrl = this.ResolveUrl("Turing.aspx");
img.Width = new Unit(140, UnitType.Pixel);
img.Height = new Unit(70, UnitType.Pixel);
LinkButton linkB = new LinkButton();
linkB.ID = "Captcha_linkB";
linkB.Text = "Can't read? Generate a new image.";
linkB.Click += new EventHandler(linkB_Click);
p1.Controls.Add(new Literal() { Text = "<table><tr><td>" });
p1.Controls.Add(l);
p1.Controls.Add(new Literal() { Text = "<br/>" });
p1.Controls.Add(img);
p1.Controls.Add(new Literal() { Text = "<br/>" });
p1.Controls.Add(tb);
p1.Controls.Add(new Literal() { Text = "<br/>" });
p1.Controls.Add(linkB);
p1.Controls.Add(new Literal() { Text = "</td></tr></table>" });
return p1;
}
void linkB_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Image img = FindControl("Captcha_Img") as System.Web.UI.WebControls.Image;
img.ImageUrl = "Turing.aspx";
}
發生什麼事情是,當我試圖生成一個新的圖像它不會做「Turing.aspx」page_load任何想法爲什麼?
更新:我將元素動態地添加到頁面,其中一個是驗證碼,其代碼可用於此鏈接Captcha,我做的唯一更改是動態創建驗證碼元素,如您在「私人面板buildCaptchaElement(XmlNode節點)「,並添加鏈接按鈕來生成一個新的圖像。
產生圖像的代碼是這樣的:
public class Turing1 : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
Bitmap objBMP =new System.Drawing.Bitmap(60,20);
Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Green);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Bold);
string randomStr="";
int[] myIntArray = new int[5] ;
int x;
//That is to create the random # and add it to our string
Random autoRand = new Random();
for (x=0;x<5;x++)
{
myIntArray[x] = System.Convert.ToInt32 (autoRand.Next(0,9));
randomStr+= (myIntArray[x].ToString());
}
//This is to add the string to session cookie, to be compared later
Session.Add("randomStr",randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.White, 3, 3);
//' Set the content type and return the image
Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
}
另一個建議:你應該把你的驗證碼變成一個用戶控件。 – 2010-03-23 13:20:45
您還應該使用「using」語句而不是顯式調用Dispose()。 – 2010-03-23 13:21:38
你也可以發佈.aspx頁面的標題嗎? – 2010-03-23 13:22:28