ASP.NET MVC验证码功能实现代码

时间:2021-05-26

前台
复制代码 代码如下:
<img id="vcodeimg" src="/Home/VCode" width="70"
height="25" />
&nbsp;<span
style="cursor: pointer; text-decoration: underline">换一张</span>

控制器
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utility;
using Jellal**;
namespace sjlwebsite.Controllers
{
public class CommonController : Controller
{
#region 验证码
[OutputCache(Duration = 0)]
public ActionResult VCode()
{
string code = ValidateCode.CreateRandomCode(4);
Session["vcode"] = code;
ValidateCode.CreateImage(code);
return View();
}

public string GetCode()
{
return Session["vcode"].ToStr();
}
#endregion
}
}

验证码类
复制代码 代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Utility
{
/// <summary>
/// 完美随机验证码 0.10
/// Verion:0.10
/// Description:随机生成设定验证码,并随机旋转一定角度,字体颜色不同
/// </summary>
public class ValidateCode
{

/// <summary>
/// 生成随机码
/// </summary>
/// <param name="length">随机码个数ic Sans MS", "Arial", "宋体" };
for (int i = 0; i < chars.Length; i++)
{
int cindex = rand.Next(7);
int findex = rand.Next(5);
Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小)
Brush b = new System.Drawing.SolidBrush(c[cindex]);
Point dot = new Point(16, 16);
//graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);//测试X坐标显示间距的
float angle = rand.Next(-randAngle, randAngle);//转动的度数
graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
graph.RotateTransform(angle);
graph.DrawString(chars.ToString(), f, b, 1, 1, format);
//graph.DrawString(chars.ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format);
graph.RotateTransform(-angle);//转回去
graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
}
//graph.DrawString(randomcode,fontstyle,new SolidBrush(Color.Blue),2,2); //标准随机码
//生成图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "image/gif";
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
graph.Dispose();
map.Dispose();
}

}
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章