C# 网页生成随机验证码
C#生成随机验证码 我要做一个注册页面,随机验证码应该如何生成,以及如何验证验证码, 验证码包含字母和数字请告诉指教...
C# 生成随机验证码 我要做一个注册页面,随机验证码应该如何生成,以及如何验证验证码, 验证码包含字母和数字请告诉指教
展开
3个回答
展开全部
新建一个web窗体。下面是后台。没有前台。直接运行。看看在符不符合你的要求
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 FeiBoLaiTe.Admin
{
public partial class Yanzhengma : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenImg(GenCode(4));
}
}
private string GenCode(int num)
{
string[] source ={"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"};
string code = "";
Random rd = new Random();
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
return code;
}
//生成图片
private void GenImg(string code)
{
Bitmap myPalette = new Bitmap(45, 16);//定义一个画板
Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例
Rectangle rc = new Rectangle(0, 0, 45, 16);//定义一个矩形
gh.FillRectangle(new SolidBrush(Color.CornflowerBlue), rc);//填充矩形
gh.DrawString(code, new Font("宋体", 13), new SolidBrush(Color.White), rc);//在矩形内画出字符串
myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
Session["code"] = code;//将字符串保存到Session中,以便需要时进行验证
gh.Dispose();
myPalette.Dispose();
}
}
}
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 FeiBoLaiTe.Admin
{
public partial class Yanzhengma : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GenImg(GenCode(4));
}
}
private string GenCode(int num)
{
string[] source ={"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"};
string code = "";
Random rd = new Random();
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
return code;
}
//生成图片
private void GenImg(string code)
{
Bitmap myPalette = new Bitmap(45, 16);//定义一个画板
Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例
Rectangle rc = new Rectangle(0, 0, 45, 16);//定义一个矩形
gh.FillRectangle(new SolidBrush(Color.CornflowerBlue), rc);//填充矩形
gh.DrawString(code, new Font("宋体", 13), new SolidBrush(Color.White), rc);//在矩形内画出字符串
myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来
Session["code"] = code;//将字符串保存到Session中,以便需要时进行验证
gh.Dispose();
myPalette.Dispose();
}
}
}
展开全部
验证码不是你想的那样直接生成字母和数字的随机数,他生成后还要压缩成图片 再前台用图片现实 这就是验证码 像你说的这种 有验证码跟无验证码是没什么区别的 很容易注入
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
建立个验证码生成的页面。。在需要调用的页面调用就好了。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询