.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 ...
随机推荐
- 鼠标指向GridView某列显示DIV浮动列表
需求: 当GRIDVIEW数据列过多,不方便全部显示在同一行或者一些子信息需要鼠标指向某关键列GRIDVIEW的时候显示其子信息. 设计:先把需要显示的浮动数据一次过抓取出来.而不是鼠标指向的时候才从 ...
- VPW协议解析
http://www.dpfdoctor.net/content/?220.html SAE J1850 VPW协议也是OBD II标准中的一种,通常应用于GM车系中. VPW英文全称是Variabl ...
- 手游产品经理初探(六)粗糙的logo会给产品致命一击
假设你的游戏产品从logo的设计開始就不注重细节的话,那么你的产品将不会走多远! 我们把图片放大看: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbGl1 ...
- 关于Javascript的内存泄漏问题的整理稿
写了好长时间javascript小功能模块,从来没有关注过内存泄漏问题.记得以前写C++程序的时候,内存泄漏是个严重的问题,我想是时候关注一下了.网上找了篇文章,Mark一下.原文地址:http:// ...
- Ajax 无刷新在注册用户名时的应用的代码
var xmlHttp; uName() //用户名失去焦点时 { if(all.uname.=="") { all.l1.innerHTML="不能为空!"; ...
- iOS的WebView中使用javascript调用原生的api
1. 首先在javascript中加入相关代码 $('.content .saveCode').on('touchstart', function () {//touchstart if (temp ...
- Codeforces Round #290 (Div. 2) D. Fox And Jumping dp
D. Fox And Jumping 题目连接: http://codeforces.com/contest/510/problem/D Description Fox Ciel is playing ...
- hdu 5265 pog loves szh II STL
pog loves szh II Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php? ...
- 泛型Dictionary的用法详解
泛型最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的 ...
- Visual Studio原生开发的10个调试技巧(一)
最近碰巧读了Ivan Shcherbakov写的一篇文章,<11个强大的Visual Studio调试小技巧>.这篇文章只介绍了一些有关Visual Studio的基本调试技巧,但是还有其 ...