1、验证码帮助类

namespace IdeaCore.Services.Common
{
public class ValidateCodeService : IValidateCodeService
{
private const string ValidateCodeKey = "ValidateCode";
private const double Pi2 = 6.283185307179586476925286766559;
private const string BackColor = "#dde3ec"; /// <summary>
/// 获取验证码的sessionkey
/// </summary>
/// <returns></returns>
public string GetValidateCodeKey() {
return ValidateCodeKey;
} /// <summary>
/// 生成验证码
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public string CreateValidateCode(int length)
{
string code = string.Empty; while (true)
{
var s = (Guid.NewGuid() + "").Substring(, );
if (s == "" || s == "l" || s == "o" || s == "")
{ }
else
{
code += s;
} if (code.Length >= length)
{
break;
}
}
return code;
} /// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="validateCode">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
const int fSize = ;
const int fWidth = fSize + ; int imageWidth = validateCode.Length * fWidth + + * ;
const int imageHeight = fSize * + ; Color[] colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
string[] fonts = { "Arial", "Georgia" }; var image = new Bitmap(imageWidth, imageHeight);
Graphics g = Graphics.FromImage(image);
try
{
g.Clear(ColorTranslator.FromHtml(BackColor));
var rand = new Random(); ////给背景添加随机生成的燥点
//Pen pen = new Pen(Color.RoyalBlue, 0);
// int c = 6 * 20; //杂点数量
// for (int i = 0; i < c; i++)
// {
// int x = rand.Next(image.Width);
// int y = rand.Next(image.Height);
// g.DrawRectangle(pen, x, y, 1, 1);
// } const int n1 = (imageHeight - - * );
const int n2 = n1 / ;
const int top1 = n2;
const int top2 = n2 * ; //随机字体和颜色的验证码字符
for (int i = ; i < validateCode.Length; i++)
{
int cindex = rand.Next(colors.Length - );
int findex = rand.Next(fonts.Length - ); var f = new Font(fonts[findex], fSize, FontStyle.Bold);
Brush b = new SolidBrush(colors[cindex]); var top = i % == ? top2 : top1; var left = i * fWidth;
if (i == ) { left += ; } g.DrawString(validateCode.Substring(i, ), f, b, left, top);
}
//
image = TwistImage(image, true, new Random().Next(, ), new Random().Next(, )); var stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
} #region 产生波形滤镜效果 /// <summary>
/// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)
/// </summary>
/// <param name="srcBmp">图片路径</param>
/// <param name="bXDir">如果扭曲则选择为True</param>
/// <param name="dMultValue"></param>
/// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
/// <returns></returns>
private static Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
var destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); // 将位图背景填充为白色
var graph = Graphics.FromImage(destBmp);
graph.FillRectangle(new SolidBrush(ColorTranslator.FromHtml(BackColor)), , , destBmp.Width, destBmp.Height);
graph.Dispose(); double dBaseAxisLen = bXDir ? destBmp.Height : destBmp.Width; for (int i = ; i < destBmp.Width; i++)
{
for (int j = ; j < destBmp.Height; j++)
{
var dx = bXDir ? (Pi2 * j) / dBaseAxisLen : (Pi2 * i) / dBaseAxisLen;
dx += dPhase;
var dy = Math.Cos(dx); // 取得当前点的颜色
int nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
int nOldY = bXDir ? j : j + (int)(dy * dMultValue); var color = srcBmp.GetPixel(i, j);
if (nOldX >= && nOldX < destBmp.Width
&& nOldY >= && nOldY < destBmp.Height)
{
destBmp.SetPixel(nOldX, nOldY, color);
}
}
} return destBmp;
}
#endregion
}
}

2、获取验证码

/// <summary>
/// 获取验证码
/// </summary>
/// <returns></returns>
public FileContentResult GetValidateCode()
{
var code = _validateCodeService.CreateValidateCode();
var bytes = _validateCodeService.CreateValidateGraphic(code);
HttpContext.Session.SetString(_validateCodeService.GetValidateCodeKey(), code);
return File(bytes, @"image/jpeg");
}

3、验证验证码

/// <summary>
/// 验证验证码
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
protected bool ValidateCode(string code) {
if (string.IsNullOrEmpty(code)) {
return false;
} var sessionCode = HttpContext.Session.GetString("ValidateCode");
return sessionCode != null && sessionCode == code.Trim();
}

.Net Core Session验证码的更多相关文章

  1. 网站启动SSL, http变为https后,session验证码错误解决方法

    网站启动SSL, http变为https后,session验证码错误解决方法   最近公司需要后台启动安全证书,证书安装完毕后,后台老提示 验证码错误,经过几天的研究,此问题已经得到有效解决,现把方法 ...

  2. net core体系-web应用程序-4net core2.0大白话带你入门-10asp.net core session的使用

    asp.net core session的使用   Session介绍 本文假设读者已经了解Session的概念和作用,并且在传统的.net framework平台上使用过. Asp.net core ...

  3. IT咨询顾问:一次吐血的项目救火 java或判断优化小技巧 asp.net core Session的测试使用心得 【.NET架构】BIM软件架构02:Web管控平台后台架构 NetCore入门篇:(十一)NetCore项目读取配置文件appsettings.json 使用LINQ生成Where的SQL语句 js_jquery_创建cookie有效期问题_时区问题

    IT咨询顾问:一次吐血的项目救火   年后的一个合作公司上线了一个子业务系统,对接公司内部的单点系统.我收到该公司的技术咨询:项目启动后没有规律的突然无法登录了,重新启动后,登录一断时间后又无法重新登 ...

  4. .net core session部分浏览器或移动客户端不可用

    .net core session使用有很多文章,这里不再赘述. 问题现象为大部分浏览器或者移动客户端(例如微信.支付宝.钉钉)等都可以正常使用.但部分支付宝用户及钉钉用户确无法使用. 写入后读取不到 ...

  5. asp.net core session丢失问题排查

    最近公司采用asp.net core的站点在外测环境中,总是发现存在session丢失的情况.排查了好久,客户端.AspNetCore.Session的cookie未丢失,session的分布式缓存采 ...

  6. .NET Core Session的简单使用

    前言 在之前的.NET 里,我们可以很容易的使用Session读取值.那今天我们来看看 如何在.NET Core中读取Session值呢? Session 使用Session之前,我们需要到Start ...

  7. asp.net core 图片验证码,后台验证

    验证方法: public static string VerificationCodeCacheFormat="vcode_cache_{0}"; public IActionRe ...

  8. .NET Core Session的使用方法

    刚使用.NET Core会不习惯,比如如何使用Session:不仅需要引用相应的类库,还需要在Startup.cs里进行注册. 1.在你的项目上基于NuGet添加: install-package M ...

  9. asp.net core session的使用

    Session介绍 本文假设读者已经了解Session的概念和作用,并且在传统的.net framework平台上使用过. Asp.net core 1.0好像需要单独安装,在nuget控制台,选择你 ...

随机推荐

  1. 用python3实现linux的sed功能

    sed是一个很好的文件处理工具,本身是一个管道命令,主要是以行为单位进行处理,可以将数据行进行替换.删除.新增.选取等特定工作.现在用python简单实现sed的主要命令,将old_text替换为ne ...

  2. android获取系统版本号

    应用场景:1.在界面中显示应用程序的版本号:2.用户启动该应用,后台判断该应用是否是最新版本.上述情景都需要在程序中自动获取到应用的版本号. 思路简介:在Android中,应用程序的版本号是在Andr ...

  3. Intellij Idea使用频率较高的几个快捷键

    自动补全参数定义: Ctrl+Alt+V 运行断点Expression: Alt+F8 选择具体的方法以断点步入:Shift+F7 智能操作: Alt+Enter 打开最近文件:Ctrl+E 打开最近 ...

  4. css3制作3d旋转相册

    此处只是记录,解析可见原文:http://www.cnblogs.com/skyblue-li/p/6092799.html <!DOCTYPE html> <html xmlns= ...

  5. Dylans loves numbers

    Problem Description Who is Dylans?You can find his ID in UOJ and Codeforces. His another ID is s1451 ...

  6. MessageBox.Show()时MessageBoxIcon的显示

    MessageBox.Show()方法,有个参数是MessageBoxIcon,这个是通过图标来表明提示信息的类型,比如一般.警告.错误等 MessageBoxIcon是一个枚举 所有成员如图: 示例 ...

  7. linux面试

    1.用户进程间通信主要哪几种方式 (1)管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信.(2)命名管道(named pipe):命名管道克服 ...

  8. oracle数据库 参数open_cursors和session_cached_cursor详解!

    open_cursors 每个session(会话)最多能同时打开多少个cursor(游标) session_cached_cursor 每个session(会话)最多可以缓存多少个关闭掉的curso ...

  9. inception cenOS 安装

    inception手册http://mysql-inception.github.io/inception-document/install/ 执行命令sh inception_build.sh,ce ...

  10. js 仿 asp中的 asc 和 chr 函数的代码

    <script type="text/javascript">var str;var asc; str = "A";document.write(s ...