asp.net动态验证码(Core中生成二维码的方法)
asp.net动态验证码(Core中生成二维码的方法)初始化界面以及二维码资源生成方法:1 <div style="text-align:center"> 2 <div style="margin-top:20px"> 3 <span>扫码获取</span><br/> 4 <img id="barcode" width="400" height="400" alt="扫码获取" src="Dynpass/GetBarCode"/> 5 </div> 6 </div>src="Dynpass/GetBarCode"表示image数据从DynpassController的GetB
本文主要介绍如何在.net环境下,基于Asp.Net Core,利用ZXing来生成二维码的一般操作。对二维码工作原理了解,详情见:https://blog.csdn.net/weixin_36191602/article/details/82466148文章介绍。
1、前期准备
.net core preview8,vs2019(用于支持core3.0),二维码生成插件:开源库ZXIng。相关插件可以在github上找到。安装vs2019后新建.net core web解决方案,也可以右键该解决方案,通过管理解决方案Nuget包功能来找到。如下图:浏览中搜索Zxing第一个既是。选中安装即可。
可通过项目中依赖性查看相应包的引用。如图:
2.二维码生成
2.1前端页面
在login.cshtml页面中添加前端元素,主要是一个图片控件。
1 <div style="text-align:center">
2 <div style="margin-top:20px">
3 <span>扫码获取</span><br/>
4 <img id="barcode" width="400" height="400" alt="扫码获取" src="Dynpass/GetBarCode"/>
5 </div>
6 </div>
src="Dynpass/GetBarCode"表示image数据从DynpassController的GetBarCode方法获取。
2.1后端代码
初始化界面以及二维码资源生成方法:
1 public class DynPassController : Controller
2 {
3 private readonly BarCodeVue _barCodeContent;//
4 public DynPassController(IOptions<BarCodeVue> content)
5 {
6 this._barCodeContent = content.Value;
7 }
8
9 /// <summary>
10 /// 初始化显示页面
11 /// </summary>
12 /// <returns></returns>
13 [HttpGet]
14 public IActionResult Login()
15 {
16 return View();
17 }
18
19 /// <summary>
20 /// Svn显示==请求获取二维码资源
21 /// </summary>
22 /// <returns></returns>
23 [HttpGet]
24 public ActionResult GetBarCode()
25 {
26 var bar= _barCodeContent != null ? _barCodeContent.BarCode : "扫码获取";
27 Bitmap bitmap = MyZxingBarcode.GenerateBitmapCode(bar);//扫码获取
28 System.IO.MemoryStream ms = new System.IO.MemoryStream();
29 bitmap.Save(ms ImageFormat.Bmp);
30 return File(ms.GetBuffer() "image/png");//
31 }
32 }
DynPassController生成二维码的内容即_barCodeContent值由core框架依赖注入(构造该对象时通过构造函数传入)。所以需在ConfigureServices中进行注册。
Barcode类结构
1 public class BarCodeVue
2 {
3 public string BarCode { get; set; }
4 }
二维码内容注册
具体步骤:
1.在appsettings.json中添加节点。
1 {
2 "Logging": {
3 "LogLevel": {
4 "Default": "Information"
5 "Microsoft": "Warning"
6 "Microsoft.Hosting.Lifetime": "Information"
7 }
8 }
9 "BarCodeVue": {
10 "BarCode":"MyBarCode"
11 }
12
13 "AllowedHosts": "*"
14 }
2.BarCodeVue注册
在Program类中ConfigureServices方法中通过Configure注册。
1 // This method gets called by the runtime. Use this method to add services to the container.
2 public void ConfigureServices(IServiceCollection services)
3 {
4 services.Configure<CookiePolicyOptions>(options =>
5 {
6 // This lambda determines whether user consent for non-essential cookies is needed for a given request.
7 options.CheckConsentNeeded = context => true;
8 });
9 services.Configure<BarCodeVue>(Configuration.GetSection("BarCodeVue"));//注册BarCodeVue键值
10 //services.AddMvc().AddViewOptions(options => options.HtmlHelperOptions.ClientValidationEnabled = true);
11 services.AddControllersWithViews()
12 .AddNewtonsoftJson();
13 services.AddRazorPages();
14 }
3.生成二维码方法MyZxingBarcode类
public class MyZxingBarcode
{
/// <summary>
/// 生成二维码 保存成图片
/// </summary>
public static Bitmap GenerateBitmapCode(string content)
{
var writer = new BarcodeWriterPixelData();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions();
options.DisableECI = true;
//设置内容编码
options.CharacterSet = "UTF-8";
//设置二维码的宽度和高度
options.Width = 300;
options.Height = 300;
//设置二维码的边距 单位不是固定像素
options.Margin = 1;
writer.Options = options;
//
var pixdata = writer.Write(content);
var map = PixToBitmap(pixdata.Pixels pixdata.Width pixdata.Height);
//string filename = @"D:\generate1.png";
//map.Save(filename ImageFormat.Bmp);
return map;
}
/// <summary>
/// 将一个字节数组转换为位图
/// </summary>
/// <param name="pixValue">显示字节数组</param>
/// <param name="width">图像宽度</param>
/// <param name="height">图像高度</param>
/// <returns>位图</returns>
private static Bitmap PixToBitmap(byte[] pixValue int width int height)
{
//// 申请目标位图的变量,并将其内存区域锁定
var m_currBitmap = new Bitmap(width height PixelFormat.Format32bppArgb);
var m_rect = new Rectangle(0 0 width height);
var m_bitmapData = m_currBitmap.LockBits(m_rect ImageLockMode.WriteOnly PixelFormat.Format32bppRgb);
IntPtr iptr = m_bitmapData.Scan0; // 获取bmpData的内存起始位置
//// 用Marshal的Copy方法,将刚才得到的内存字节数组复制到BitmapData中
System.Runtime.InteropServices.Marshal.Copy(pixValue 0 iptr pixValue.Length);
m_currBitmap.UnlockBits(m_bitmapData);
//// 算法到此结束,返回结果
return m_currBitmap;
////初始化条形码格式,宽高,以及PureBarcode=true则不会留白框
//var writer = new BarcodeWriterPixelData
//{
// Format = BarcodeFormat.QR_CODE
// Options = new ZXing.Common.EncodingOptions { Height = 31 Width = 167 PureBarcode = true Margin = 1 }
//};
//var pixelData = writer.Write("123236699555555555559989966");
//using (var bitmap = new Bitmap(pixelData.Width pixelData.Height PixelFormat.Format32bppRgb))
//using (var ms = new MemoryStream())
//{
// var bitmapData = bitmap.LockBits(new Rectangle(0 0 pixelData.Width pixelData.Height)
// System.Drawing.Imaging.ImageLockMode.WriteOnly PixelFormat.Format32bppRgb);
// try
// {
// // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image
// System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels 0 bitmapData.Scan0 pixelData.Pixels.Length);
// }
// finally
// {
// bitmap.UnlockBits(bitmapData);
// }
// // save to stream as PNG
// bitmap.Save(ms ImageFormat.Png);
// Image image = Bitmap.FromStream(ms true);
// image.Save(@"D:\content.png");
// byte[] bytes = ms.GetBuffer();
//}
}
}
运行生成结果: