转贴:自己写的一个图形验证码页面(Asp.Net2.0通过)
项目需要,要在首页登录界面添加一个图形验证码,赶时髦吧,网上一搜,特别多,找了几个,都不太满意。主要问题是大部分代码生成的图片宽度不唯一,页面布局不容易控制,其次是颜色单一,有些又过于抽象,不仔细看很容易弄错。针对特定的客户,我只需要“图片”长宽固定,颜色多样的数字图形验证码,借鉴网上的现有代码,自己操刀完成,以下是效果图:原理不复杂,就是把网页当画布,运用各色画笔,在特定区域内画出数字,然后以特定格式(本例为PNG格式)发回客户端,在IE中显示为"图片",用于验证的字符串存于Session中。
主要代码如下:
public string GetRandomNumberString( int int_NumberLength)
{
string str_Number = string.Empty;
Random theRandomNumber = new Random();
for (int int_index = 0; int_index < int_NumberLength; int_index++)
str_Number += theRandomNumber.Next(10).ToString();
return str_Number;
}
生成随机颜色
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
// 对于C#的随机数,没什么好说的
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
// 为了在白色背景上显示,尽量生成深色
int int_Red = RandomNum_First.Next(256);
int int_Green = RandomNum_Sencond.Next(256);
int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
根据验证字符串生成最终图象
{
int int_ImageWidth = str_ValidateCode.Length * 13;
Random newRandom = new Random();
// 图高20px
Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
Graphics theGraphics = Graphics.FromImage(theBitmap);
// 白色背景
theGraphics.Clear(Color.White);
// 灰色边框
theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, 19);
// 10pt的字体
Font theFont = new Font("Arial", 10);
for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
{
string str_char = str_ValidateCode.Substring(int_index, 1);
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point(int_index * 13 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
theGraphics.DrawString(str_char, theFont, newBrush, thePos);
}
// 将生成的图片发回客户端
MemoryStream ms = new MemoryStream();
theBitmap.Save(ms, ImageFormat.Png);
Response.ClearContent(); //需要输出图象信息 要修改HTTP头
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
theGraphics.Dispose();
theBitmap.Dispose();
Response.End();
}
最后在Page_Load中调用以上代码
{
if(!IsPostBack)
{
// 4位数字的验证码
string str_ValidateCode = GetRandomNumberString(4);
// 用于验证的Session
Session["ValidateCode"] = str_ValidateCode;
CreateImage(str_ValidateCode);
}
}
使用的时候在页面中加入一个Image,将图片路径改为ValidateCode.aspx的相对路径即可
{
TextBox1.Text = "正确!";
}
else
TextBox1.Text = " 错误! " ;
OK,基本搞定,总结一下:
优点:1. 简单明了,适于简单运用
2. 界面友好,图片长宽格式固定
缺点:1. 如果有多个页面都需要此验证码,则会导致Session被其它页面重写的情况,可以考虑指定具体Session值为效验值
2. 暂时只支持数字,不过更改GetRandomNumberString()中的代码可以实现指定字符机的随机字符串
3. 页面刷新后验证码随之改变
抛砖引玉,欢迎各位博友评点
一 格式化gridview
和asp.net 1.1一样,gridview可以很方便地定制其样式,比如css,颜色等。要定制gridview的格式,十分简单,只需要鼠标右击gridview,在弹出的菜单中选择"AUTO FORMAT",则可以选择gridview的样式,内置了许多样式,如下图:
如果你要对gridview中每一列自定义格式,则只需要点击gridview右上角的"smart tag"智能标记,在弹出的菜单中,选择"edit columns",会弹出如下图的窗体,这样就可以对每列进行详细的设置了:
比如,如果要某一列设置为特殊格式,如要将unitprice设置为货币格式,可以在unitprice列的DataFormatString属性中设置为{0:C},程序代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="productsDataSource"
Runat="server"
SelectCommand="SELECT [ProductID], [ProductName],
[QuantityPerUnit], [UnitPrice], [UnitsInStock] FROM
[Products]"
ConnectionString="<%$ ConnectionStrings:NWConnectionString %>"
DataSourceMode="DataReader">
</asp:SqlDataSource>
<asp:GridView ID="productGridView" Runat="server"
DataSourceID="productsDataSource"
DataKeyNames="ProductID" AutoGenerateColumns="False"
BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510" BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True" BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:BoundField ReadOnly="True" HeaderText="ID" InsertVisible="False" DataField="ProductID"
SortExpression="ProductID">
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="ProductName" SortExpression="ProductName">
</asp:BoundField>
<asp:BoundField HeaderText="Qty/Unit"
DataField="QuantityPerUnit"
SortExpression="QuantityPerUnit"></asp:BoundField>
<asp:BoundField HeaderText="Price/Unit"
DataField="UnitPrice" SortExpression="UnitPrice"
DataFormatString="{0:c}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Units In Stock" DataField="UnitsInStock"
SortExpression="UnitsInStock"
DataFormatString="{0:d}">
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundField>
</Columns>
<SelectedRowStyle ForeColor="White" Font-Bold="True"
BackColor="#738A9C"></SelectedRowStyle>
<RowStyle ForeColor="#8C4510" BackColor="#FFF7E7"></RowStyle>
</asp:GridView>
</div>
</form>
</body>
</html>
程序运行后结果如下:
而有的时候,我们可能要根据需要,对gridview中的数据进行特殊的显示,比如当某样商品库存为0时,要求gridview中以不同颜色进行显示,这时,可以按如下的方法进行:
首先,gridview提供了rowdatabound事件,该事件在gridview中每行被创建并且绑定到datasource控件后被触发,因此,我们可以利用该事件去检查库存是否为0,如果为0的话,将所在行的北京颜色设置为黄色,代码如下:
GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int unitsInStock = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "UnitsInStock"));
if (unitsInStock == 0)
e.Row.BackColor = Color.Yellow;
}
}
首先,该事件首先检查,当前的行是否属于datarow类型的行,因为象gridview中的headerrow,footerrow等行,并不包含实际的数据,因此,我们不需要使用headerrow和footerrow,而为了取得库存unitesinstock的内容,通过使用databinder.eval的方法取出其内容,并转换为int类型,接着判断是否为0,如果为0的话,则设置其行的背景颜色为黄色。程序运行结果如下图所示: