.Net (MVC) 随机生成验证码
以前一直对C#的GDI画图部分知识点不怎么用所以忘得差不多了,这两天正好公司要做一个博客系统,其中一个需求就是留言时为了防止恶意攻击必须填写验证码,正好借着这个机会复习了一下,以下是实现代码,写的比较简单。
View 层
@{
ViewBag.Title = "Home Page";
}
<div class="row">
<h1>test</h1>
<div class="col-lg-12">
@using(Html.BeginForm("Index","Home", FormMethod.Post, new {@id="form",@enctype = "multipart/form-data" }))
{
<div class="form-group">
<input type="file" name="file"/>
<input type="file" name="files" />
<button>提交</button>
</div>
<div class="form-group">
<div class="col-lg-1">
<input type="text" class="col-lg-3"/>
</div>
<div class="col-lg-3">
<img id="img" onclick="CheckCode()" src="/Home/GetValidateCode" style="height:30px;width:110px" title="点击更换" alt="点击更换" />
<a href="javascript:void(0)" onclick="CheckCode()">点击更换</a>
</div>
</div>
}
</div>
</div>
@section scripts{
<script>
$(function () {
$("#img").click(function () {
CheckCode()
})
})
function CheckCode() {
$("#img").attr("src", "/Home/GetValidateCode?date="+new Date());
}
</script>
}
Controller 层
/// <summary>
/// View页面请求获得验证码
/// </summary>
public void GetValidateCode()
{
//获取随机生成的编码
string ValiDateCode = GetValiDateCode();
Session["Key"] = ValiDateCode;
byte[] bytes = GetValidateCode(ValiDateCode);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(bytes);
// 也可以用MVC 的FileResult
//return File(bytes, @"image/jpeg");
} /// <summary>
/// 生成验证码方法
/// </summary>
/// <param name="ValiDateCode"></param>
/// <returns></returns>
public static byte[] GetValidateCode(string ValiDateCode)
{
Bitmap img = new Bitmap((int)Math.Ceiling(ValiDateCode.Length * 12.6), ); //创建 Bitmap对象
Graphics graphics = Graphics.FromImage(img); //创建 Graphics 对象
graphics.Clear(Color.White); //清空图片背景色
Random random = new Random(); //创建 Random 实例
for (int i = ; i <= ; 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);
graphics.DrawLine(new Pen(Color.Silver),x1, y1, x2, y2); //在图片上画噪点线
}
Font font = new Font("Arial", ,(FontStyle.Bold));
//创建 Brush 对象, LinearGradientBrush实现字体渐变效果 LinearGradientBrush(Rectangle rectangle,Color color1,Color color2,float angle, bool isAngleScaleable)
LinearGradientBrush linear = new LinearGradientBrush(new Rectangle(, , img.Width, img.Height), Color.Gray, Color.Blue, 1.4f, true);
graphics.DrawString(ValiDateCode, font, linear, , ); //绘制生成的验证码,
graphics.DrawRectangle(new Pen(Color.Silver), , , img.Width - , img.Height - );
MemoryStream stream = new MemoryStream(); //创建 流对象
img.Save(stream, ImageFormat.Jpeg); //将图像以特定的格式保存到流对象中
return stream.ToArray();
} /// <summary>
/// 获取随机生成的验证码
/// </summary>
/// <returns></returns>
private static string GetValiDateCode()
{
string[] letter = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "i", "m", "n", "o", "p", "Q" };
Random random = new Random();
StringBuilder result = new StringBuilder();
for (int i = ; i <= ; i++)
{
if (i % == )
{
result.Append(letter[random.Next(, )]);
}
else
{
result.Append(random.Next(, ));
}
}
return result.ToString();
}
效果图:

.Net (MVC) 随机生成验证码的更多相关文章
- Python随机生成验证码的两种方法
Python随机生成验证码的方法有很多,今天给大家列举两种,大家也可以在这个基础上进行改造,设计出适合自己的验证码方法方法一:利用range Python随机生成验证码的方法有很多,今天给大家列举两种 ...
- Android锁定EditText内容和随机生成验证码
昨天写了个小Demo,实现了随机生成验证码,和锁定EditText两个小功能,先看一下效果图: 锁定EditText在我们不须要用户编辑EditText内容的时候能够用到,实现还是非常easy的,一行 ...
- 随机生成验证码及python中的事务
1.随机生成验证码 # import random # print(random.random()) #-1的小数 # print(random.randint(,)) #包括1和3 # print( ...
- js随机生成验证码以及随机颜色
Javascript通过Math.random()随机生成验证码. 代码如下: <!DOCTYPE html><html> <head> <meta char ...
- 随机生成验证码(JS)
效果展示 实现原理 1. html:一般就是一个div: <div id="code"></div> ,样式根据需求设计. 2. JS:1)将所有的验证码所 ...
- php随机生成验证码代码
<?php session_start(); //产生一个随机的字符串验证码 $checkcode=""; for ($i=0;$i<4;$i++){ $checkco ...
- js随机生成验证码及其颜色
今天迎来了2018年第一场雪,这个美好的日子,总的写点什么纪念一下,在这里写了一个在js中使用Math.random()函数,随机生成四位数的验证码及其验证码换颜色. js代码如下: var arra ...
- Djaingo 随机生成验证码(PIL)
基础: https://www.cnblogs.com/wupeiqi/articles/5812291.html 实例: https://www.cnblogs.com/6324TV/p/88112 ...
- java随机生成验证码
package com.yuyuchen.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; im ...
随机推荐
- 通过点击取消按钮关闭dialog窗口
- GitHub 上排名前 100 的 Android 开源库进行简单的介绍
若有任何疑问可通过邮件或微博联系我 项目名称 项目简介 1. react-native 这个是 Facebook 在 React.js Conf 2015 大会上推出的基于 JavaScript 的开 ...
- PL/pgSQL学习笔记之三
http://www.postgresql.org/docs/9.1/static/plpgsql-overview.html 39.1.2. Supported Argument and Resul ...
- c# 轻量级 ORM 框架 之 Model解析 (四)
关于orm框架设计,还有必要说的或许就是Model解析了,也是重要的一个环节,在实现上还是相对比较简单的. Model解析,主要用到的技术是反射了,即:把类的属性与表的字段做映射. 把自己的设计及实现 ...
- 【S17】使用“swap技巧”除去多余的容量
1.考虑下面的需求,对于vec开始的时候有1000个元素,后来只有10个元素,那么vec的capacity至少还是1000,后面的990个内存单元,没有使用,但是还被vec霸占着.如何释放这些内存呢? ...
- CodeForces 163A Substring and Subsequence dp
A. Substring and Subsequence 题目连接: http://codeforces.com/contest/163/problem/A Description One day P ...
- CodeForces 176C Playing with Superglue 博弈论
Playing with Superglue 题目连接: http://codeforces.com/problemset/problem/176/C Description Two players ...
- Codeforce Gym 100015I Identity Checker 暴力
Identity Checker 题目连接: http://codeforces.com/gym/100015/attachments Description You likely have seen ...
- 【JavaScript】XMLHttpRequest Level2使用指南
XMLHttpRequest是一个浏览器接口,使得Javascript可以进行HTTP(S)通信. 最早,微软在IE 5引进了这个接口.因为它太有用,其他浏览器也模仿部署了,ajax操作因此得以诞生. ...
- ActivityGroup+LinearLayout实现iphone风格的底部tab菜单
public class ActsGroup extends ActivityGroup { private LinearLayout bodyView; private Line ...