业务处理类里面的代码:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using QRCoder;
namespace WanLian.Common
{
/// <summary>
///
/// </summary>
public interface IQRCode
{
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="pixel"></param>
/// <returns></returns>
Bitmap GetQRCode(string url, int pixel);
}
/// <summary>
///
/// </summary>
public class RaffQRCode : IQRCode
{
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="url"></param>
/// <param name="pixel"></param>
/// <returns></returns>
public Bitmap GetQRCode(string url, int pixel)
{
var generator = new QRCodeGenerator();
var qrCodeData = generator.CreateQrCode(url, QRCodeGenerator.ECCLevel.Q);
var qrCode = new QRCoder.QRCode(qrCodeData);
var bitmap = qrCode.GetGraphic(pixel);
return bitmap;
}
}
}
控制器里面处理代码:
IQRCode qrCode;
private Db provider = Db.Instance;
/// <summary>
/// 会员
/// </summary>
public RegisterController(IConfiguration configuration,IQRCode qrCode)
{
this.configuration = configuration;
this.qrCode = qrCode;
}
[HttpGet("GetQrCode")]
public IActionResult Get(string url, int pixel)
{
if (string.IsNullOrEmpty(url))
{
return BadRequest("parameter is null");
}
if (pixel <= 0)
{
return BadRequest("pixel <= 0");
}
var bitmap = qrCode.GetQRCode(url, pixel);
var ms = new MemoryStream();
bitmap.Save(ms, ImageFormat.Jpeg);
return File(ms.GetBuffer(), "image/jpeg");
}
在项目的start.cs文件里面的 改动
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ThreeDimensionalSetting>(Configuration.GetSection("ThreeDimensionalSetting"));
services.AddTransient<IQRCode, RaffQRCode>(); --此处是生成二维码用到的
services.AddMvc();
}
前端页面使用生成二维码显示在界面:
jQuery("#wxImg").attr("src", "http://" + window.location.host + "/api/register/GetQrCode?url=http://" + window.location.host + "/member/NewRegister&pixel=10");
<img src="http://120.55.13.190:9005/api/register/GetQrCode?url=http://120.55.13.190:9005/member/NewRegister&pixel=10" id="wxImg">
上面图片控件处就会显示一个二维码然后用手机扫一扫会自动跳转到newregister页面。即配置的url就是扫码后要跳转到的页面,而且是微信端打开的页面。如果是文字那么会在微信端打开一个空白页面上面显示配置的文字内容