基于Layui+mvc登录界⾯验证码
html
<form class="layui-form" role="form" method="post">
<div>
<table align="center">
<tr>
<td >
<input type="text" name="code" id="code" required lay-verify="required" placeholder="验证码"class="layui-input">
</td>
<td >
<img id="checkloing" src="/Login/VCode" title="看不清,换⼀张"
/>
</td>
</tr>
<tr>
<td colspan="2">
<button id="loginBtn"class="layui-btn layui-btn-lg layui-btn-normal" lay-submit lay-filter="loginBtn">⽴即登录</button>                </td>
</tr>
</table>
</div>
</form>
js
layui.use('form', function () {
var form = layui.form;
var layer = layui.layer;
var $ = layui.jquery
//layui表单提交⽅法
<('submit(loginBtn)', function (data) {
var user = data.field;
$.post('/Login/Login', user, function (res) {
if ("success" == res)//如果成功则跳转到指定页⾯
location.href = "/Home/";
//location.href = "/pageChange/pageChange";
else {//失败则弹出失败提⽰
layer.msg(res, {
offset: 1,
shift: 0,
area: ['100%', '50px'],
time: 3000,
scrollbar: false,
}, function () {//在登录失败时刷新验证码
var str = "?" + Math.random();//加上这句话可以解决验证码不刷新
$("#checkloing").attr("src", "/Login/VCode" + str);
});
}
});
return false;
});
});
//验证码点击事件
$(document).ready(function (e) {
$("#checkloing").click(function () {
var str = "?" + Math.random();
$(this).attr("src", "/Login/VCode" + str);
})
});
Controllers
using COMMON;
using System;
using System.Web.Mvc;
namespace SFMVC3._0.Controllers
{
public class LoginController : Controller
{
///<summary>
///登录
/
//</summary>
///<param name="code"></param>
///<returns></returns>
[HttpPost]
public string Login(string code)
{string str = Session["code"].ToString();
str = str.ToLower();
code = code.ToLower();
if (str != vccode)
{
return"验证码错误";
}
return"success";
}
///<summary>
///验证码点击事件
///</summary>
///<returns></returns>
public ActionResult VCode()
{
limitCodeHelper vcode = new limitCodeHelper();
string codeStr = vcode.GetRandomCode();
if (!string.IsNullOrEmpty(codeStr))
{
byte[] arrImg = vcode.GetVCode(codeStr);
Session["code"] = codeStr;
return File(arrImg, "image/gif");
}
else
{
return RedirectToAction("/Login/VCode?rand=" + Guid.NewGuid().ToString().Substring(1, 10), "image/jpeg");            }
}
}
}
Dal
using System;
using System.Drawing;
namespace COMMON
{
//验证码绘制
public class limitCodeHelper
{
private static Color BackColor = Color.White;
private static int Width = 100;
private static int Height = 36;
private int letterWidth = 24;//单个字体的宽度范围
private Random _random;
// private string _code;
private int _brushNameIndex;
private string[] fonts = { "Arial", "Georgia" };
public byte[] GetVCode(string codeStr)
{
_random = new Random();
Bitmap img = new Bitmap(Width, Height);
using( Graphics g = Graphics.FromImage(img)) {
Random random = new Random();
//⽩⾊背景
g.Clear(Color.White);
//画图⽚的背景噪⾳线
for (int i = 0; i < 10; i++)
{
int x1 = random.Next(img.Width);
int x2 = random.Next(img.Width);
int y1 = random.Next(img.Height);
int y2 = random.Next(img.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
//随机字体和颜⾊的验证码字符
for (int int_index = 0; int_index < codeStr.Length; int_index++)
{
string str_char = codeStr.Substring(int_index, 1);
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point(int_index * letterWidth + 1 + _random.Next(3), 1 + _random.Next(3));
g.DrawString(str_char, new Font(GetFont().FontFamily, 18, FontStyle.Bold), newBrush, thePos);
}
//灰⾊边框
//g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, Width - 1, (Height - 1));
/
/图⽚扭曲
img = TwistImage(img, true, 3, 4);
//将⽣成的图⽚发回客户端
g.DrawRectangle(Pens.DarkGray, 0, 0, Width - 1, Height - 1);//绘画边框
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
//将图⽚保存到内存流中
img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
//将内存流⾥的数据转成 byte 数组返回
return ms.ToArray();
}
}
}
///<summary>
///绘画⽂字
///</summary>
///<param name="g"></param>
private void Paint_Text(Graphics g, string code)
{
g.DrawString(code, GetFont(), GetBrush(), 3, 1);
}
///<summary>
/
//绘画⽂字噪⾳点
///</summary>
///<param name="g"></param>
private void Paint_TextStain(Bitmap b)
{
string[] BrushName = new string[] {    "OliveDrab",
"ForestGreen",
"DarkCyan",
"LightSlateGray",
"RoyalBlue",
"SlateBlue",
"DarkViolet",
"MediumVioletRed",
"IndianRed",
"Firebrick",
"Chocolate",
"Peru",
" enrod"
};
for (int n = 0; n < 30; n++)
{
int x = _random.Next(Width);
int y = _random.Next(Height);
b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));            }
}
///<summary>
///随机取⼀个字体
///</summary>
///<returns></returns>
private Font GetFont()
{
string[] FontItems = new string[]{  "Arial",
"Helvetica",
"Geneva",
"sans-serif",
"Verdana"
};
int fontIndex = _random.Next(0, FontItems.Length);
FontStyle fontStyle = GetFontStyle(_random.Next(0, 2));
return new Font(FontItems[fontIndex], 12, fontStyle);
}
/**/
/**/
/**/
/
//<summary>
///随机取⼀个笔刷
///</summary>
///<returns></returns>
private Brush GetBrush()
{
Brush[] BrushItems = new Brush[]{    Brushes.OliveDrab,
Brushes.ForestGreen,
Brushes.DarkCyan,
Brushes.LightSlateGray,
Brushes.RoyalBlue,
Brushes.SlateBlue,
Brushes.DarkViolet,
Brushes.MediumVioletRed,
Brushes.IndianRed,
Brushes.Firebrick,
Brushes.Chocolate,
Brushes.Peru,
Brushes.Goldenrod
};
int brushIndex = _random.Next(0, BrushItems.Length);
_brushNameIndex = brushIndex;
return BrushItems[brushIndex];
}
///<summary>
///绘画背景颜⾊
///</summary>
///<param name="g"></param>
private void Paint_Background(Graphics g)
{
g.Clear(BackColor);
}
/**/
/
登录页面背景图**/
/**/
///<summary>
///取⼀个字体的样式
///</summary>
///<param name="index"></param>
///<returns></returns>
private FontStyle GetFontStyle(int index)
{
switch (index)
{
case0:
return FontStyle.Bold;
case1:
return FontStyle.Italic;
default:
return FontStyle.Regular;
}
}
///<summary>
///取得⼀个 4 位的随机码
///</summary>
/
//<returns></returns>
public string GetRandomCode()
{
return Guid.NewGuid().ToString().Substring(0, 4);
}
///<summary>
///随机颜⾊
///</summary>
///<returns></returns>
public Color GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
int int_Red = RandomNum_First.Next(210);
int int_Green = RandomNum_Sencond.Next(180);
int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);// 5+1+a+s+p+x
}
///<summary>
///扭曲图⽚
/
//</summary>
///<param name="srcBmp"></param>
///<param name="bXDir"></param>
///<param name="dMultValue"></param>
///<param name="dPhase"></param>
///<returns></returns>
public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)        {
double PI = 6.283185307179586476925286766559;
Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
Graphics graph = Graphics.FromImage(destBmp);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height);
graph.Dispose();
double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
for (int i = 0; i < destBmp.Width; i++)
{
for (int j = 0; j < destBmp.Height; j++)
{
double dx = 0;
dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen;
dx += dPhase;
double dy = Math.Sin(dx);
int nOldX = 0, nOldY = 0;
nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
nOldY = bXDir ? j : j + (int)(dy * dMultValue);
Color color = srcBmp.GetPixel(i, j);
if (nOldX >= 0 && nOldX < destBmp.Width
&& nOldY >= 0 && nOldY < destBmp.Height)
{
destBmp.SetPixel(nOldX, nOldY, color);
}
}
}
srcBmp.Dispose();
return destBmp;
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。