ASP.NET 做验证码
显示验证码的界面:
前台:
<td class="style4">
验证码:</td>
<td class="style2">
<asp:TextBox ID="TextBox3" runat="server" Height="21px"></asp:TextBox>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Default2.aspx"/>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/Default.aspx">看不清换张图</asp:HyperLink>
</td>
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str = ConfigurationManager.ConnectionStrings["sqlstr"].ConnectionString;
using (SqlConnection sqlCnn=new SqlConnection(str))
{
using (SqlCommand sqlCmm=sqlCnn.CreateCommand())
{
sqlCmm.CommandText = "select * from Login";
sqlCnn.Open();
SqlDataReader reader = sqlCmm.ExecuteReader();
bool bl = false;
if (reader!=null)
{
while (reader.Read())
{
if (this.TextBox1.Text == reader["name"].ToString() && this.TextBox2.Text == reader["password"].ToString() && this.TextBox3.Text == Session["code"].ToString())
{
bl = true;
}
}
if (bl==true)
{
ClientScript.RegisterClientScriptBlock(GetType(), "提示", "<script>alert('登陆成功!')</script>");
}
else
{
ClientScript.RegisterClientScriptBlock(GetType(), "提示", "<script>alert('登陆失败!')</script>");
}
}
}
}
}
}
做验证码的界面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Text;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Image img = new Bitmap(100,20);
Graphics g = Graphics.FromImage(img);
this.DealImage(img,10);
g.DrawLine(Pens.Yellow, 0, 0, 100, 20);
string code = this.GenerateCode();
Font font = new Font("宋体", 20, FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline);
Session["code"] = code; //保存到Session中
g.DrawString(code,font,Brushes.YellowGreen,0,0);
this.Response.Clear();
MemoryStream ms = new MemoryStream();
img.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
this.Response.BinaryWrite(ms.ToArray());
this.Response.Flush();
this.Response.End();
}
private void DealImage(System.Drawing.Image img,int nums)
{
Bitmap b = img as Bitmap;
Random ran = new Random();
for (int i = 0; i < nums; i++)
{
b.SetPixel(ran.Next(0, img.Width), ran.Next(0,img.Height),Color.White);
}
}
private string GenerateCode() //产生随机数
{
Random ran = new Random(DateTime.Now.Millisecond);
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i <6; i ++)
{
sb.Append(ran.Next(0,9));
}
return sb.ToString();
}
}
摘自 淡蓝蓝蓝
相关新闻>>
- 发表评论
-
- 最新评论 更多>>