ASP.NET Core: Generate QR Code using ASP.NET Core in C#
By FoxLearn 12/27/2019 11:06:12 PM 5.66K
After you finish creating a new ASP.NET Core project. You need to create a QRCodeController
Next, Right-click on your project, then select Manage Nuget Packages => Search and Install 'QRCoder' library to your project.
QRCoder is a library qr code generator c# dll free that helps you generate qr code.
How to generate qr code in asp.net core mvc using c#
Finally, Create an Image action
//qr code in asp net core public IActionResult Image() { QRCodeGenerator qrCodeGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrCodeGenerator.CreateQrCode("Welcome to FoxLearn !", QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap bitmap = qrCode.GetGraphic(15); var bitmapBytes = ConvertBitmapToBytes(bitmap); //Convert bitmap into a byte array return File(bitmapBytes, "image/jpeg"); //Return as file result }
C# Convert image to byte array
We will convert the image into a byte array, then return to the image file.
private byte[] ConvertBitmapToBytes(Bitmap bitmap) { using (MemoryStream memoryStream = new MemoryStream()) { bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png); return memoryStream.ToArray(); } }
Press F5 to run your project, then change your url to QRCode/Image. You can see your qr code.
If you want to embed qr code inside html, you can right click on Index action, then create an Index view
Modifiding your view as the following code.
@{ ViewData["Title"] = "Index"; } <h1>Index</h1> <img src='@Url.Action("Image")' alt="qrcode" />
Press F5 again, then change your url to QRCode/Index