How to Generate QR Code in ASP.NET Core using C#
By FoxLearn 9/10/2024 8:47:02 AM 6.03K
QRCoder is a .NET library that allows you to create QR codes easily and provides various options for customization.
After you finish creating a new ASP.NET Core project. You need to create a QRCodeController, then add an action method that will generate and return the QR code image.
You need to install the QRCoder library via NuGet Package Manager by right-clicking on your project, then select Manage Nuget Packages => Search and Install 'QRCoder' library to your project
You can do this by running the following command in the Package Manager Console or by using the NuGet Package Manager UI:
Install-Package QRCoder
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" />
You can now generate QR codes by calling the URL https://yourdomain/QRCode/Index