Vue學習使用系列九【axiox全域性預設配置以及結合Asp.NetCore3.1 WebApi 生成顯示Base64的圖形驗證碼】

jason發表於2020-10-08

1:前端code

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <title>Document</title>
 8     <style type="text/css">
 9         .imgshow {
10             width: 260px;
11             height: 160px;
12             border: 1px solid #666666;
13         }
14         
15         .imgnoshow {
16             width: 80px;
17             height: 20px;
18         }
19     </style>
20     <script src="../assets/vue.js"></script>
21     <script src="../assets/axios.js"></script>
22 </head>
23 
24 <body>
25     <div id="app">
26         <div v-if="person">
27             <!--加一個判斷,防止前端報錯不能夠識別name等 person的屬性,由於載入的先後順序問題,為null時是沒有person.name等屬性-->
28             <p>name: {{person.name}}</p>
29             <p>age: {{person.age}}</p>
30             <div @click="getYanzCode" :class="imgshow"><img :src="imgshowpath" alt="not found" /></div>
31             <div><img :src="tempdata" alt="not found" /> </div>
32             <div>{{imgshowpath}}</div>
33             <div>{{tempdata}}</div>
34         </div>
35     </div>
36     <script>
37         //axiox全域性預設配置
38         axios.defaults.baseURL = "http://localhost:5000/api/"; //上下的通常就是來使用controller+action的路徑等
39         axios.defaults.timeout = 5000;
40         var app = new Vue({
41             el: "#app",
42             data: {
43                 person: null,
44                 classflag: true,
45                 imgshow: "imgshow",
46                 imgshowpath: "",
47                 tempdata: ""
48             },
49             methods: {
50                 dopost01: function() {
51                     /*
52                     後端的code
53                      [HttpPost("postdata01")]
54                     public dynamic postdata01(string name, int age)
55                     */
56                     axios({
57                         method: "post",
58                         url: "appsetjson/postdata01", //後續就可以直接寫上controller+路由名稱或者action名稱等
59                         //自動拼接成一個完整的路徑==> http://localhost:5000/api/appsetjson/postdata01?name=qq%E7%88%B1&age=19
60                         params: {
61                             name: "qq愛",
62                             age: 19
63                         }
64                     }).then(respos => {
65                         this.person = respos.data;
66                     })
67                 },
68                 dopostimg: function() {
69                     var _this = this;
70                     axios({
71                         //responseType: "arraybuffer",
72                         method: "post",
73                         url: "appsetjson/dopostimg",
74                     }).then(respos => {
75                         console.log("=>" + respos.data.data); //respos或者respos.data=>都是[object Object]
76                         _this.imgshowpath = respos.data.data; // 'data:image/png;base64,' + btoa(new Uint8Array(respos.data.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
77                         _this.tempdata = respos.data.data; // 'data:image/png;base64,' + btoa(new Uint8Array(respos.data.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
78                     })
79                 },
80                 getYanzCode: function() {
81                     this.dopostimg();
82                     return false;
83                 }
84             },
85             mounted: function() {
86                 this.dopost01();
87                 //  this.dopostimg();
88             }
89 
90         })
91     </script>
92 </body>
93 
94 </html>

2:測試效果:

 

 3:後端截圖2020-10-08的部分測試Code;

 1 using System;
 2 namespace WebApiDemo.Controllers
 3 {
 4     using Microsoft.AspNetCore.Cors;
 5     using Microsoft.AspNetCore.Mvc;
 6     using Microsoft.Extensions.Configuration;
 7     using Microsoft.Extensions.Options;
 8     using System.IO;
 9     using WebApiDemo.Filters;
10     using System.Drawing;
11     using System.Drawing.Imaging;
12 
13     [ApiController]
14     [Route("api/[controller]")]
15     [MyFilter]
16     public class AppSetjsonController : ControllerBase
17     {
18         private IConfiguration _Configuration;
19         public Person _person { get; set; }
20         public Appset01 _jwtobj { get; set; }
21         public AppSetjsonController(IConfiguration configuration, IOptions<Person> options)
22         {
23             this._Configuration = configuration;
24             this._person = options.Value;
25         }
26         [HttpGet]
27         [Route("getAppSetting")]
28         public ApiResult<Appset01> getAppSetting()
29         {
30             ApiResult<Appset01> dic = new ApiResult<Appset01>();
31             try
32             {
33                 //BindNonPublicProperties 預設為false全部獲取,true為不獲取私有的欄位
34                 dic.data = _Configuration.GetSection("Appset01").Get<Appset01>(c => c.BindNonPublicProperties = true);
35                 Console.WriteLine("addr=" + _person.addr + ",name=" + _person.name + ", book[0].name=" + _person.books[0].bname);
36                 dic.message = "獲取成功!";
37             }
38             catch (Exception ex)
39             {
40                 dic.message = "獲取失敗:" + ex.Message;
41             }
42             return dic;
43         }
44         [HttpPost("postdata01")]
45         public dynamic postdata01(string name, int age)
46         {
47             dynamic dy = new { name = name, age = age };
48             return dy;
49         }
50         [HttpPost("postdata02")]
51         public dynamic postdata02([FromBody] tempPerson person)
52         {
53             dynamic dy = new { name = person.name, age = person.age };
54             return dy;
55         }
56         [HttpPost("dopostimg")]
57         public dynamic dopostimg()
58         {
59             try
60             {
61                 return new { data = MyCodeGrapHelper.GetImgCode() };
62             }
63             catch (Exception ex)
64             {
65                 return new { data = ex.Message };
66             }
67         }
68 
69         [HttpPost("postdata03/{name}/{age}")]
70         public dynamic postdata03(string name, int age)
71         {
72             dynamic dy = new { name = name, age = age };
73             return dy;
74         }
75     }
76 
77     public class imgCodeBase64
78     {
79         public string imgPath { get; set; }
80         public string key { get; set; }
81         public int code { get; set; } = 500;
82     }
83     public class tempPerson
84     {
85         public string name { get; set; }
86         public int age { get; set; }
87     }
88 }

 4:驗證碼生成的code幫助類

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading.Tasks;
  5 
  6 namespace WebApiDemo
  7 {
  8     using System.Drawing;
  9     using System.Drawing.Imaging;
 10     using System.IO;
 11     public class MyCodeGrapHelper
 12     {
 13         /// <summary>
 14         /// 生成隨機驗證碼圖片
 15         /// </summary>
 16         /// <param name="captchaCode">隨機驗證碼</param>
 17         /// <param name="width">寬為0將根據驗證碼長度自動匹配合適寬度</param>
 18         /// <param name="height"></param>
 19         /// <returns></returns>
 20         private static MemoryStream GenerateCaptchaImage(string captchaCode, int width = 0, int height = 30)
 21         {
 22             //驗證碼顏色集合
 23             Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
 24 
 25             //驗證碼字型集合
 26             string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };
 27 
 28             //定義影像的大小,生成影像的例項
 29             var image = new Bitmap(width == 0 ? captchaCode.Length * 25 : width, height);
 30 
 31             var g = Graphics.FromImage(image);
 32 
 33             //背景設為白色
 34             g.Clear(Color.WhiteSmoke);
 35 
 36             var random = new Random();
 37             //繪製干擾點
 38             for (var i = 0; i < 40; i++)
 39             {
 40                 var x = random.Next(image.Width);
 41                 var y = random.Next(image.Height);
 42                 g.DrawRectangle(new Pen(c[random.Next(c.Length)], 0), x, y, 1, 1);
 43             }
 44 
 45             //驗證碼繪製在g中  
 46             for (var i = 0; i < captchaCode.Length; i++)
 47             {
 48                 //隨機顏色索引值 
 49                 var cindex = random.Next(c.Length);
 50 
 51                 //隨機字型索引值 
 52                 var findex = random.Next(fonts.Length);
 53 
 54                 //字型 
 55                 var f = new Font(fonts[findex], 15, FontStyle.Bold);
 56 
 57                 //顏色  
 58                 Brush b = new SolidBrush(c[cindex]);
 59 
 60                 var ii = 4;
 61                 if ((i + 1) % 2 == 0)
 62                     ii = 2;
 63 
 64                 //繪製一個驗證字元  
 65                 g.DrawString(captchaCode.Substring(i, 1), f, b, 10 + (i * 15), ii);
 66             }
 67 
 68             var ms = new MemoryStream();
 69             image.Save(ms, ImageFormat.Png);
 70 
 71             g.Dispose();
 72             image.Dispose();
 73 
 74             return ms;
 75         }
 76 
 77         public static string GetImgCode(int codelength = 4)
 78         {
 79             int[] intarry = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
 80             List<int> listtemp = new List<int>();
 81             while (listtemp.Count <= codelength)
 82             {
 83                 int code = intarry[new Random().Next(0, intarry.Length)];
 84                 if (!listtemp.Contains(code))
 85                 {
 86                     listtemp.Add(code);
 87                 }
 88             }
 89             string captchaCode = string.Join("", listtemp);
 90             MemoryStream ms = GenerateCaptchaImage(captchaCode);
 91             string arrystr = ImageToBase64(ms);
 92             ms.Dispose();
 93             return arrystr;
 94         }
 95 
 96         private static string ImageToBase64(MemoryStream src)
 97         {
 98             return "data:image/png;base64," + Convert.ToBase64String(src.ToArray());
 99         }
100     }
101 }

 

相關文章