来自  资质荣誉 2019-09-25 01:42 的文章
当前位置: 澳门太阳娱乐手机登录 > 资质荣誉 > 正文

好好彩色验证码,关于登录

1,大家在登录中时常会碰着访问系统的有些页面不能登录,要求走登录页面,就算访谈的不是登录页面,那么那是如何做的啊?以及在登入中有永不忘记作者以及验证码的输入功用。

前台代码:
 <asp:TextBox ID="tbck" runat="server" Width="107px" SkinID="worm"></asp:TextBox>
          <img alt="看不清?点击改变" onclick="this.src=this.src+'?'" src="VerifyCode.aspx" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
   
后台代码:
 if (this.tbck.Text == Request.Cookies["vCode"].Value)
        {
            Response.Write("相等");
        }

今日就写了那般二个demo关于登入验证 验证码,以及记住自个儿效力吗

//////VerifyCode.aspx
后台代码:

2,在那中最首要运用了Session 和Cookies,Cookies 存款和储蓄客商的登录新闻,Session存取验证码消息

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

登录页:Login.aspx

public partial class VerifyCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        VerifyCode v = new VerifyCode();
        v.Length = this.length;
        v.FontSize = this.fontSize;
        v.Chaos = this.chaos;
        v.BackgroundColor = this.backgroundColor;
        v.ChaosColor = this.chaosColor;
        v.CodeSerial = this.codeSerial;
        v.Colors = this.colors;
        v.Fonts = this.fonts;
        v.Padding = this.padding;
        string code = v.CreateVerifyCode();    // 取随机码
        v.CreateImageOnPage(code, this.Context);    // 输出图片
        Response.Cookies.Add(new HttpCookie("vCode", code));    // 使用Cookies取验证码的值
    }

<script>
function checkcode() {
var vcode = document.getElementById("checkcode");
vcode.src = vcode.src + '1';
}
window.onload = function () {
var did = document.getElementById.style.width;
did = window.innerWidth - 100;
}
</script>

    //验证码长度(默许6个验证码的长度)
    int length = 4;
    public int Length
    {
        get { return length; }
        set { length = value; }
    }

<form runat="server" method="post">
用户名:<input type="text" name="username" value="<%=username %>" />
<br />
<br />
密 码:<input type="password" name="upwd" value="<%=upwd %>" />
<br />
验证码:<input type="text" name="Vcode" />
<img src="ValidateCode.ashx?1" />
<a href="Javascript:checkcode()">看不清,换一张</a>
<br />
<br />
<div >
<div style="margin: 0 auto">
记住我:<input type="checkbox" name="echeck" />
</div>
</div>
<br />
<input type="submit" value="登陆" />
</form>

    //验证码字体大小(为了显示扭曲功效,暗中认可20像素,能够自动修改)
    int fontSize = 12;
    public int FontSize
    {
        get { return fontSize; }
        set { fontSize = value; }
    }

登录管理:Login.aspx.cs

    //边框补(默认1像素)
    int padding = 1;
    public int Padding
    {
        get { return padding; }
        set { padding = value; }
    }

public partial class Login : System.Web.UI.Page
{
protected string username { get; set; }
protected string upwd { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
string vcode=Request["Vcode"];
//页面第一次加载,假设验证码为空,取缓存
if (string.IsNullOrEmpty
{
HttpCookie cooike = Request.Cookies["jun"];
if (cooike!= null) {
string uinfo = Encoding.UTF8.GetString(Convert.FromBase64String(cooike.Value));
username = uinfo.Split[0];
upwd = uinfo.Split[1];
}
}
else {
if (vcode != null)
{
if (vcode.Equals(Session["vcode"].ToString(), StringComparison.CurrentCultureIgnoreCase))
{
//验证码正确
string sql = "select count from tb_Userinfo where userName=@uname and userpwd=@upwd";
SqlParameter[] ps = new SqlParameter[] {
new SqlParameter("@uname",Request["username"]),
new SqlParameter("@upwd",Request["upwd"])
};
int count = Convert.ToInt32(SqlHelper.ExecuteScalar;
//客户音信正确
if (count > 0)
{
//假使勾中切记本身
if (!string.IsNullOrEmpty(Request["echeck"]))
{
//登录成功,存取Cookies新闻
string uinfo = Request["username"] + "_" + Request["upwd"];
//转成64位编码
uinfo = Convert.ToBase64String(Encoding.UTF8.GetBytes;
HttpCookie cooike = new HttpCookie("jun", uinfo)
{
Expires = DateTime.Now.AddDays
};
Response.Cookies.Add;
}
Session["userinfo"] = 1;
Response.Redirect("Index.aspx");
}
else
{
Response.Write("客商名或密码错误");
}
}
else
{
Response.Write;
}
}
}
}
}

    //是或不是输出燥点(默以为出口)
    bool chaos = true;
    public bool Chaos
    {
        get { return chaos; }
        set { chaos = value; }
    }

得逞后转到Index页面 转到页面首先走Index承继的SessionStatus类 大家在那在那之中封装三个艺术

    //输出燥点的颜色(私下认可洋红)
    Color chaosColor = Color.LightGray;
    public Color ChaosColor
    {
        get { return chaosColor; }
        set { chaosColor = value; }
    }

protected void p_load(object sender, EventArgs e)
{
if (Session["userinfo"] == null)
{
Response.Redirect("Login.aspx");
}
}

    //自定义背景观(暗中同意棕色)
    Color backgroundColor = Color.White;
    public Color BackgroundColor
    {
        get { return backgroundColor; }
        set { backgroundColor = value; }
    }

在Login.aspx.cs页面先存款和储蓄Session["userinfo"]=1 那样就会变成非登录页验证是或不是合法登录了

    //自定义随机颜色数组
    Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
    public Color[] Colors
    {
        get { return colors; }
        set { colors = value; }
    }

验证码小编重要引用一个相似管理程序:ValidateCode.ashx

    //自定义字体数组
    string[] fonts = { "Arial", "Georgia" };
    public string[] Fonts
    {
        get { return fonts; }
        set { fonts = value; }
    }

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
CreateImage(CreateRandomCode.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
//发生随机码
private string CreateRandomCode(int iLength)
{
int rand;
char code;
string randomCode = String.Empty;

    //自定义随机码字符串种类(使用逗号分隔)
   // string codeSerial = "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 codeSerial = "0,1,2,3,4,5,6,7,8,9";

//生成必然长度的验证码
System.Random random = new Random();
for (int i = 0; i < iLength; i++)
{
rand = random.Next();
if (rand%3==0)
{
code = ('A' + (rand % 26));
}
else
{
code = ('0'+;
}
randomCode += code.ToString();
}

    public string CodeSerial
    {
        get { return codeSerial; }
        set { codeSerial = value; }
    }

Console.WriteLine("--------------------------"+HttpContext.Current.Session.SessionID);
HttpContext.Current.Session["vcode"] = randomCode;
return randomCode;
}
//创设随机图片
private Image CreateImage(string strVerifyCode)
{
Bitmap map;
try
{
int iRandAngle = 45; //随机转动角度
int iMapWidth = (strVerifyCode.Length * 21);
map = new Bitmap(iMapWidth, 28); //创制图片背景

    //生成人事教育育高校验码图片
    public Bitmap CreateImageCode(string code)
    {
        int fSize = FontSize;
        int fWidth = fSize + Padding;

Graphics graph = Graphics.FromImage;
graph.Clear(Color.艾丽丝Blue);//清除画面,填充背景

        int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
        int imageHeight = fSize * 2 + Padding;

graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式

        System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);

Random rand = new Random();

        Graphics g = Graphics.FromImage(image);

//背景噪点生成
Pen blackPen = new Pen(Color.LightGray, 0);
for (int i = 0; i < 50; i++)
{
int x = rand.Next(0, map.Width);
int y = rand.Next(0, map.Height);
graph.DrawRectangle(blackPen, x, y, 1, 1);
}

        g.Clear(BackgroundColor);

//验证码旋转,幸免机器度和胆识别
char[] chars = strVerifyCode.ToCharArray();//拆散字符串成单字符数组

        Random rand = new Random();

//文字距中
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;

        //给背景增多随机变化的燥点
        if (this.Chaos)
        {
            Pen pen = new Pen(ChaosColor, 0);
            int c = Length * 15;

//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//定义字体
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };

            for (int i = 0; i < c; i++)
            {
                int x = rand.Next(image.Width);
                int y = rand.Next(image.Height);

for (int i = 0; i < chars.Length; i++)
{
int cindex = rand.Next;
int findex = rand.Next;

                g.DrawRectangle(pen, x, y, 1, 1);
            }
        }

Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式
Brush b = new System.Drawing.SolidBrush(c[cindex]);

        int left = 0, top = 0, top1 = 1, top2 = 1;

Point dot = new Point;

        int n1 = (imageHeight - FontSize - Padding * 2);
        int n2 = n1 / 4;
        top1 = n2;
        top2 = n2 * 2;

float angle = rand.Next(-iRandAngle, iRandAngle);//转动的度数

        Font f;
        Brush b;

graph.TranslateTransform(dot.X, dot.Y);//移动光标到钦点地点
graph.RotateTransform;
graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);

        int cindex, findex;

graph.RotateTransform;//转回去
graph.TranslateTransform(2, -dot.Y);//移动光标到内定地方
}

        //随机字体和颜料的验证码字符
        for (int i = 0; i < code.Length; i++)
        {
            cindex = rand.Next(Colors.Length - 1);
            findex = rand.Next(Fonts.Length - 1);

graph.DrawRectangle(new Pen(Color.Black, 0), -chars.Length * 18, 0, map.Width - 1, map.Height - 1);//画三个边框

            f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
            b = new System.Drawing.SolidBrush(Colors[cindex]);

}
catch (ArgumentException ex)
{
map = null;
throw ex;
}
return map;
}
public bool IsReusable
{
get
{
return false;
}
}

            if (i % 2 == 1)
            {
                top = top2;
            }
            else
            {
                top = top1;
            }

            left = i * fWidth;

            g.DrawString(code.Substring(i, 1), f, b, left, top);
        }

        //画二个边框 边框颜色为Color.White
        g.DrawRectangle(new Pen(Color.White, 0), 0, 0, image.Width - 1, image.Height - 1);
        g.Dispose();

        return image;
    }

    //将创造好的图片输出到页面
    public void CreateImageOnPage(string code, HttpContext context)
    {
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        Bitmap image = this.CreateImageCode(code);

        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

        context.Response.ClearContent();
        context.Response.ContentType = "image/jpeg";
        context.Response.BinaryWrite(ms.GetBuffer());

        ms.Close();
        ms = null;
        image.Dispose();
        image = null;
    }

    //生成随机字符码
    public string CreateVerifyCode(int codeLen)
    {
        if (codeLen == 0)
        {
            codeLen = Length;
        }

        string[] arr = CodeSerial.Split(',');

        string code = "";

        int randValue = -1;

        Random rand = new Random(unchecked((int)DateTime.Now.Ticks));

        for (int i = 0; i < codeLen; i++)
        {
            randValue = rand.Next(0, arr.Length - 1);

            code += arr[randValue];
        }

        return code;
    }

    public string CreateVerifyCode()
    {
        return CreateVerifyCode(0);
    }
}

 

 

 

 

 

 

 

 

 

 /// <summary>
/// 数学算式的验证码  
///  
///  Author: DeltaCat (三角猫)
/// </summary>

public sealed class MathVerifyCode
{
    #region 生成图片

    /// <summary>
    /// 输出验证码表明式到浏览器
    /// </summary>
    /// <param name="context">httpcontext</param>
    /// <param name="sessionKey">保存运算值的SESSION的KEY</param>
    public void OutputImage(System.Web.HttpContext context, string sessionKey)
    {
        int mathResult = 0;
        string expression = null;

        Random rnd = new Random();

        ////生成3个10以内的整数,用来运算
        int operator1 = rnd.Next(0, 10);
        int operator2 = rnd.Next(0, 10);
        int operator3 = rnd.Next(0, 10);

        ////随机组合运算顺序,只做 + 和 * 运算
        switch (rnd.Next(0, 3))
        {
            case 0:
                mathResult = operator1 + operator2 * operator3;
                expression = string.Format("{0} + {1} * {2} = ?", operator1, operator2, operator3);
                break;
            case 1:
                mathResult = operator1 * operator2 + operator3;
                expression = string.Format("{0} * {1} + {2} = ?", operator1, operator2, operator3);
                break;
            default:
                mathResult = operator2 + operator1 * operator3;
                expression = string.Format("{0} + {1} * {2} = ?", operator2, operator1, operator3);
                break;
        }

        using (Bitmap bmp = new Bitmap(150, 25))
        {
            using (Graphics graph = Graphics.FromImage(bmp))
            {
                graph.Clear(Color.FromA#e8eef7); ////背景观,可活动安装

                ////画噪点
                for (int i = 0; i <= 128; i++)
                {
                    graph.DrawRectangle(
                        new Pen(Color.FromArgb(rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255))),
                        rnd.Next(2, 128),
                        rnd.Next(2, 38),
                        1,
                        1);
                }

                ////输出表明式
                for (int i = 0; i < expression.Length; i++)
                {
                    graph.DrawString(expression.Substring(i, 1),
                        new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold),
                        new SolidBrush(Color.FromArgb(rnd.Next(255), rnd.Next(128), rnd.Next(255))),
                        5 + i * 10,
                        rnd.Next(1, 5));
                }

                ////画边框,不需求能够注释掉
                graph.DrawRectangle(new Pen(Color.Firebrick), 0, 0, 150 - 1, 25 - 1);
            }

            context.Session[sessionKey] = mathResult; ////将运算结果存入session

            ////禁止使用缓存
            DisableHttpCache(context);

            ////输出图片到浏览器,笔者使用的是 gif 格式,可自动安装任何格式
            context.Response.ContentType = "image/gif";
            bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.End();
        }
    }

    #endregion

    /// <summary>
    /// 禁止使用缓存
    /// </summary>
    /// <param name="context">httpcontext</param>
    private static void DisableHttpCache(System.Web.HttpContext context)
    {
        ////清除http缓存
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        ////禁用http缓存
        //// http 1.1
        context.Response.AddHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
        context.Response.AddHeader("Cache-Control", "no-store, no-cache, max-age=0, must-revalidate");
        //// http 1.0
        context.Response.AddHeader("Pragma", "no-cache");
    }
}

注: 若是认为验证码太模糊,能够将画噪点的地方调解为上面包车型大巴:

                for (int i = 0; i <= 128; i++)
                {
                    graph.DrawRectangle(
                        new Pen(Color.FromArgb(rnd.Next(0, 255), rnd.Next(0, 255), rnd.Next(0, 255))),
                        (float)rnd.Next(2, 128),
                        (float)rnd.Next(2, 38),
                        0.5F, //噪点的粒度
                        0.5F);//噪点的粒度,能够调治那八个值,到感觉本身从心所欲
                }

//新建贰个 ashx 页面,比如: Mvc.ashx
//记得此ashx文件的类,必定要承继 System.Web.SessionState.IRequiresSessionState 才可以行使session

public class Mvc : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest (HttpContext context) {
        MathVerifyCode mvc = new MathVerifyCode();
        mvc.OutputImage(context, "mvc");
    }

    public bool IsReusable {
        get {
            return true;
        }
    }
}

在急需出示验证码的地方,参加:

<img src="mvc.aspx" alt=""/>或者<img src="mvc.ashx" alt=""/>

 

 

本文由澳门太阳娱乐手机登录发布于 资质荣誉,转载请注明出处:好好彩色验证码,关于登录

关键词: