C# 一般处理程序ashx用于验证码
生活随笔
收集整理的這篇文章主要介紹了
C# 一般处理程序ashx用于验证码
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1、用VS2019建立一個(gè)web應(yīng)用程序,選mvc模板
2、選中項(xiàng)目郵件新建文件夾Webservice,然后添加一般處理程序Verify.ashx然后右鍵打開(kāi)改寫(xiě)如下
1 public class VerifyCode : IHttpHandler, IRequiresSessionState
2 {
3
4 public bool IsReusable { get { return false; } }
5 private const int width = 90;
6 private const int height = 30;
7 public void ProcessRequest(HttpContext context)
8 {
9 context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
10 context.Response.ClearContent();
11 context.Response.ContentType = "image/Png";
12 context.Response.BinaryWrite(CreateImg(ExfSoft.Common.SecurityUtil.CreateNew(4, true)));
13 context.Response.End();
14 }
15
16 private byte[] CreateImg(string VerifyCode)
17 {
18 //這個(gè)寬高可以根據(jù)需要確定
19 System.Drawing.Bitmap image = new Bitmap(width, height);
20 //創(chuàng)建圖形
21 Graphics g = Graphics.FromImage(image);
22 //創(chuàng)建RectangleF結(jié)構(gòu)指定一個(gè)區(qū)域
23 RectangleF rectangle = new RectangleF(0, 0, image.Width, image.Height);
24 g.FillRectangle(new SolidBrush(Color.FromArgb(255, 255, 255)), rectangle);
25
26 //背景噪音線
27 System.Random random = new Random();
28 for (int i = 0; i < 15; i++)
29 {
30 int x1 = random.Next(width);
31 int x2 = random.Next(width);
32 int y1 = random.Next(height);
33 int y2 = random.Next(height);
34 g.DrawLine(new Pen(Color.FromArgb(random.Next())), x1, y1, x2, y2);
35 }
36 Font font = new Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
37 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, width, height), Color.Blue, Color.DarkRed, 1.2f, true);
38
39 var chars = new List<Char>();
40 foreach (char s in VerifyCode)
41 {
42 chars.Add(s);
43 }
44
45 g.DrawString(String.Join(" ", chars.ToArray()), font, brush, 10, 5);
46
47 //畫(huà)圖片的前景噪音點(diǎn)
48 for (int i = 0; i < 50; i++)
49 {
50 int x = random.Next(width);
51 int y = random.Next(height);
52 image.SetPixel(x, y, Color.FromArgb(random.Next()));
53 }
54 //畫(huà)圖片的邊框線
55 g.DrawRectangle(new Pen(Color.FromArgb(255, 153, 193, 226)), 0, 0, image.Width - 1, image.Height - 1);
56
57 MemoryStream ms = new MemoryStream();
58 //選擇透明格式
59 image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
60 //原本是準(zhǔn)備輸出html流,現(xiàn)在輸出圖信數(shù)據(jù),所以要修改http頭
61 return ms.ToArray();
62 }
63 }
3、任意找一個(gè)頁(yè)面如Index.cshtml,添加圖片控件和Jquery代碼
<img id="verifycode_img" src="/webservice/verifycode.ashx" onclick="" style="vertical-align: middle; margin-left: 10px;" />
<script>
$(function () {
$("#verifycode_img").click(function () {
$(this).attr('src', '/WebService/VerifyCode.ashx?t=' + new Date())
})
})
</script>
4、效果,點(diǎn)擊圖片驗(yàn)證碼將會(huì)做相應(yīng)變化
5、配合input框提交到后臺(tái)Action里面通過(guò),ExfSoft.Common.SecurityUtil.IsValid("驗(yàn)證碼字符串")方法,即可以實(shí)現(xiàn)登錄驗(yàn)證碼功能。
總結(jié)
以上是生活随笔為你收集整理的C# 一般处理程序ashx用于验证码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: rest_framework之解析器详解
- 下一篇: 【编程思想】C# delegate 委托