从现在开始我会将我学习的东西一点一点的写到博客上与大家分享,一是我在写的过程中能更加熟练,二希望让刚开始学习asp.net的同学可以参考。
因为我本人也是刚刚接触asp.net还是个菜鸟,有错误之处还希望能留言,十分感谢!
动态生成验证码实例:
1. 首先在前台写好相应的代码:
<table><tr><td>
<img src ="CodeHandler.ashx" id ="image"/>
</td><td><asp:LinkButton runat = "server" text="更换验证码!"</td></tr></table>
2. 有了这些外海需要加上一些js代码,这样才能保证不会刷新整个页面
<script type="text/javascript>
function changcode(){
var src = CodeHandler.ashx?time= date();
document.GetelementByid("image").src= src;
}
3.在项目中添加一个一般处理程序
private static System.Random random = new Random();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "Image/jpeg";
//创建位图
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100,50);
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
//上颜色
g.Clear(System.Drawing.Color.Beige);
string CodeString = random.Next(1000, 10000).ToString();
context.Session["Code"] = CodeString;
//设置字体位置
System.Drawing.StringFormat sf = new System.Drawing.StringFormat();
sf.Alignment = System.Drawing.StringAlignment.Center;
sf.LineAlignment = System.Drawing.StringAlignment.Center;
g.DrawString(CodeString,
new System.Drawing.Font("Arial",16),
System.Drawing.Brushes.DarkKhaki,
new System.Drawing.Rectangle(0,0,bitmap.Width,bitmap.Height),
sf);
}
bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
}