注意命名空间的引用

在项目中新建Validcode.aspx

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="false"%><%@ Import Namespace="System.Drawing" %><%@ Import Namespace="System.Drawing.Drawing2D" %><%@ Import Namespace="System.Drawing.Imaging" %><%@ Import Namespace="System.IO" %><%@ Import Namespace="System.Text" %><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>验证码</title><!--禁止浏览器从本地缓存中调阅页面--><meta http-equiv="pragram" content="no-cache" /><!--必须重新加载页面--><meta http-equiv="cache-control" content="no-cache, must-revalidate" /><!--网页在缓存中的过期时间--><meta http-equiv="expires" content="-1" /><script type="text/C#" runat="server">/** 使用方法* <img id="imgValidateCode" border="1" src="ValidateCode.aspx" style="cursor:hand" οnclick="this.src='ValidateCode.aspx?'+Math.random()" title="点击更换验证码" />*/static readonly char[] codeList = new char[]{'0','1','2','3','4','5','6','7','8','9'};string sessionKey = "ValidateCode";//保存在Session中所用的KEYint codeLength = 4;                //验证码字符长度  int width = 64;                   //验证码图片宽度int height = 20;                   //验证码图片高度int fontSize = 13;                 //验证码字体大小
protected void Page_Load(object sender, EventArgs e){//获取验证码字符串
string strCode = GetValidateCode();//将验证码字符串保存到Session中
Session[sessionKey] = strCode;//实例化图片
using (Bitmap img = new Bitmap(width, height)){//获取画板
using (Graphics g = Graphics.FromImage(img)){//填充底纹//                    g.FillRectangle(new HatchBrush(HatchStyle.Horizontal, Color.LightYellow, Color.LightSkyBlue), 0, 0, width, height);
                    g.Clear(Color.LightCyan);Random rand = new Random();for (int i = 0; i < 150; i++){int x = rand.Next(img.Width);int y = rand.Next(img.Height);g.DrawPie(new Pen(Color.LightGray, 0f), x, y, 4, 4, 1, 1);} //绘制验证码
using (Font font = new Font("Rockwell", fontSize, FontStyle.Bold | FontStyle.Italic)){g.DrawString(strCode, font, new LinearGradientBrush(new Point(0, 0), new Point(0, 5), Color.Blue, Color.Chocolate), (width - font.SizeInPoints * codeLength) / 2, (height - font.SizeInPoints) / 3);}using (MemoryStream mStream = new MemoryStream()){//将图片存入内存中
img.Save(mStream, ImageFormat.Gif);//将图片输出至页面
Response.ClearContent();Response.ContentType = "image/gif";Response.BinaryWrite(mStream.ToArray());}}}Response.End();}//生成验证码
public string GetValidateCode(){Random rand = new Random();StringBuilder strBuilder = new StringBuilder(codeLength);for (int i = 0; i < codeLength; i++){strBuilder.Append(codeList[rand.Next(0, codeList.Length)]);}return strBuilder.ToString();}</script></head><body></body></html>

客户端

<form id="form1" runat="server"><ul><li><asp:TextBox ID="txt_LoginName" runat="server"   class="loginuser" ></asp:TextBox></li><li><asp:TextBox ID="txt_PassWord" runat="server" class="loginpwd"  TextMode ="Password"></asp:TextBox></li><li><label>验证码:</label><asp:TextBox ID="txt_CheckCode" runat="server" class="loginBox" style="width: 100px;" type="text" CssClass="loginCode" size="20" maxlength="15"></asp:TextBox><img  align="absmiddle" id="Img1" style="cursor: pointer;"   src="Validcode.aspx?k=" alt="验证码" title="看不清,换张图片?" onclick="this.src+=Math.random();" /><label>点击图片刷新</label> </li>
<li>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="请输入登录名" ControlToValidate="txt_LoginName" Display="Dynamic" Width="74px"></asp:RequiredFieldValidator><asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txt_LoginName" Display="Dynamic" ErrorMessage="登录名不正确" onservervalidate="CustomValidator1_ServerValidate" Width="72px"></asp:CustomValidator><asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="请输入密码" ControlToValidate="txt_PassWord" Display="Dynamic" Width="62px"></asp:RequiredFieldValidator><asp:CustomValidator ID="CustomValidator2" runat="server" ControlToValidate="txt_PassWord" Display="Dynamic" ErrorMessage="密码不正确" onservervalidate="CustomValidator2_ServerValidate" Width="62px"></asp:CustomValidator><asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="请输入验证码" ControlToValidate="txt_CheckCode" Display="Dynamic" Width="73px" ></asp:RequiredFieldValidator><asp:CustomValidator ID="CustomValidator3" runat="server" ControlToValidate="txt_CheckCode" Display="Dynamic" ErrorMessage="验证码不正确" onservervalidate="CustomValidator3_ServerValidate" Width="73px"></asp:CustomValidator></li><li><asp:Button ID="Button1" runat="server" Text="登录" class="loginbtn" value="登录"  onclick="Button1_Click" /><label><input name="" type="checkbox" value="" checked="checked" />记住密码</label><label><a href="Reg.aspx">点此注册会员</a></label></li></ul></form>

服务端

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.Web.Services;public partial class Manage_Login : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e){}protected void Button1_Click(object sender, EventArgs e){if (Page.IsValid){string Password = txt_PassWord.Text.ToString().Trim().Replace("'", "''").Replace("=", "");string UserID = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");Password = func.md5(Password);string CheckCode = txt_CheckCode.Text.ToString().Trim();UserID = UserID.Replace("'", "''").Replace("=", "");string sql = "select * from DeviceUser where LoginName='" + UserID + "' and IsChecked = 1 ";DataTable dt = new DataTable();dt = db.GreatDs(sql).Tables[0];if (dt.Rows.Count > 0){string pw1 = dt.Rows[0]["Password"].ToString();if (Password == dt.Rows[0]["Password"].ToString()){string ID = dt.Rows[0]["ID"].ToString();DateTime datetime = DateTime.Now;//定义时间对象HttpCookie DeviceUserIDcookie = System.Web.HttpContext.Current.Response.Cookies["DeviceUserID"];DeviceUserIDcookie.Values.Add("ID",dt.Rows[0]["ID"].ToString().Trim()) ;DeviceUserIDcookie.Values.Add("LoginTime", datetime.ToString());TimeSpan ts = new TimeSpan(1, 0, 0, 0);//cookie有效作用时间,具体查msdnDeviceUserIDcookie.Expires = datetime.Add(ts);//添加作用时间
System.Web.HttpContext.Current.Response.AppendCookie(DeviceUserIDcookie);//确定写入cookie中
                    Response.Redirect("index.aspx");}}}}protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){string LoginName = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");LoginName = LoginName.Replace("'", "''").Replace("=", "");string sql = "select count(id) from DeviceUser  where LoginName='" + LoginName + "'  and IsChecked = 1 ";int Count = int.Parse(db.ExeSQLs(sql));if (Count == 0){args.IsValid = false;}else{args.IsValid = true;}}protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args){string Password = txt_PassWord.Text.ToString().Trim().Replace("'", "''").Replace("=", "");string LoginName = txt_LoginName.Text.ToString().Trim().Replace("'", "''").Replace("=", "");Password = func.md5(Password);string CheckCode = txt_CheckCode.Text.ToString().Trim();LoginName = LoginName.Replace("'", "''").Replace("=", "");string sql = "select * from DeviceUser   where LoginName='" + LoginName + "'  ";DataTable dt = new DataTable();dt = db.GreatDs(sql).Tables[0];if (dt.Rows.Count > 0){string pw1 = dt.Rows[0]["Password"].ToString();if (Password == pw1){args.IsValid = true;}else{args.IsValid = false;}}else{args.IsValid = true;}}protected void CustomValidator3_ServerValidate(object source, ServerValidateEventArgs args){if (args.Value != ""){string CheckCode = args.Value;string ValidateCodeSession = "";if (Session["ValidateCode"] != null){ValidateCodeSession = Session["ValidateCode"].ToString();} if (CheckCode == ValidateCodeSession){args.IsValid = true;}else{args.IsValid = false;}}}}

转载于:https://www.cnblogs.com/mobobo/p/5630284.html

C# 生成验证码 方法一相关推荐

  1. php excel header,【IT专家】PHP生成excel,方法一-header生成

    本文由我司收集整编,推荐下载,如有疑问,请与我司联系 PHP生成excel,方法一:header生成 2018/02/09 444 public function export_order() { / ...

  2. java生成验证码的三种方法

    java生成验证码的三种方法 第一种:导入jar包com.github.axet生成法 ①导包 <dependency><groupId>com.github.axet< ...

  3. JBOSS通过Apache负载均衡方法一:使用mod_jk

    JBOSS通过Apache负载均衡方法一:使用mod_jk   本文第一.二节分别对Linux环境下前端使用Apache以及windows环境下前端使用IIS通过AJP协议和后端的JBOSS通信实现负 ...

  4. J2EE如何生成验证码图片和点击刷新验证码

    验证码图片生成步骤 创建BufferedImage对象. 获取BufferedImage的画笔,即调用getGraphics()方法获取Graphics对象. 调用Graphics对象的setColo ...

  5. HTML 转 PDf 方法一 wkhtmltopdf.exe

    工作中涉及到制作PDF报表,找了很多办法,总是不尽人意,有诸多bug,如: 1:中文显示乱码 2:处理字符串分割及换行时要么是字符串被截断无法显示,要么就是无法换行超出显示范围 3:处理分页是内容被截 ...

  6. Windows c# 生成验证码图片

    1.生成类CodeImageUtil using System; using System.Drawing; using System.IO;namespace sdp_share_pjt {publ ...

  7. 图像抖动(加入随机噪声+矩阵有序抖动)Java实现,不使用OpenCV 按照课堂中讲的两种抖动(Dithering)方法,自己编程实现(编程语言不限)。实现方法一:以加入随机噪声的方式保留信息

    下面这个题我做了好久,老师说用不到OpenCV,所以我觉得应该用编程读取文件的操作,但我又不知道用C++或者Java如何读取图片文件,所以这里对于我来说是一个问题,当我发现读取文件之后,我又不知道怎么 ...

  8. php直播源码,生成验证码并提交验证

    php直播源码,生成验证码并提交验证的相关代码 一般处理程序(WaterMark.ashx)中代码 using System; using System.Collections.Generic; us ...

  9. 仿比心源码,生成验证码并提交验证

    仿比心源码,生成验证码并提交验证实现的相关代码 一般处理程序(WaterMark.ashx)中代码 using System; using System.Collections.Generic; us ...

最新文章

  1. 图解字符串的朴素模式匹配算法
  2. 易创课堂深圳干货,趁热下载
  3. mysql Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nona
  4. YBTOJ:前缀数组(KMP)
  5. latex 多行公式_Markdown中输入多行并列的公式
  6. linux-facl权限控制-移除-复制
  7. 【知了堂学习笔记】数据库连接池简介,以及Eclipse中C3p0连接池的简单运用
  8. Python3与OpenCV3.3 图像处理(九)--高斯模糊
  9. dHedge DAO和一些顶级基金向基金管理者投资14.5万sUSD
  10. oracle的exp程序,数据库expimp迁移的整个过程,及注意事项
  11. 机械制造技术基础【3】
  12. material文本框与按钮边框旋转效果实现登录页面
  13. 清算(清分)与结算的区别
  14. SQL合并 合并id相同的数据
  15. 局域网arp攻击_图解ARP协议(三)ARP防御篇-如何揪出“内鬼”并“优雅的还手”...
  16. Java学习笔记01—Java概述、数据类型、变量、标识符、类型转换
  17. CESIUM学习—— viewer.trackedEntity小坑坑
  18. Java复习之抽象类和接口
  19. HLJUOJ1117(暴力模拟)
  20. 产品经理必看电影:操作系统革命 Revolution OS

热门文章

  1. 又拍云黄慧攀QCon 2016技术分享:直播平台架构与实施
  2. dedecms后台崩溃或者后台访问慢的解决方法
  3. oracle10g遇到ORA-16038日志无法归档问题
  4. UBUNTU修改控制台语言
  5. python栈应用_栈应用之 后缀表达式计算 (python 版)
  6. java string对象放在什么区域_java中String对象的存储位置
  7. css3切角文本框_CSS3:linear-gradient切角画册
  8. 12linux目录结构13Linux目录详解
  9. Python机器学习:PCA与梯度上升:007试手MNIST数据集
  10. java 正则 js_正则表达式在js和java中如何使用