asp.net ajax implements no refresh captcha
- 2020-05-16 06:40:34
- OfStack
1. The first is the event code in Page_Load of the background verification code aspx file:
2. Next, define an JS function on the page where the captcha is displayed
3. Then edit the foreground page aspx. Below is the code snippet of the foreground page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
namespace Student online examination system
{
public partial class AjaxAutoCode : System.Web.UI.Page
{
// Verify the digital
public string authcode = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
#region The first 1 A method for generating captcha
Random random = new Random();
authcode = random.Next(1111, 9999).ToString();
// Construct images
Bitmap image = new Bitmap(authcode.Length * 12, 25);
// Create a canvas
Graphics g = Graphics.FromImage(image);
try
{
g.Clear(Color.White);
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);
// A line connecting two points
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkBlue, 1.2f, true);
g.DrawString(authcode, font, brush, 2, 2);
// Draw the foreground noise of the picture
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()));
}
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
ms.WriteTo(this.Response.OutputStream);
ms.Close();
this.Response.ContentType = "image/gif";
}
finally
{
image.Dispose();
g.Dispose();
}
#endregion
}
}
}
2. Next, define an JS function on the page where the captcha is displayed
function fGetCode()
{
document.getElementById("getcode").src="Default2.aspx?"+Math.random();
}
3. Then edit the foreground page aspx. Below is the code snippet of the foreground page
<label> Verification code </label>
<asp:TextBox ID="txt_checkCode" runat="server" Width="178px"></asp:TextBox>
<img src="Default2.aspx" alt=" Can't see? " id="getcode"/> <a href="javascript:fGetCode()"> Replace verification code </a>