ASP.NET Core: Generate QR Code using ASP.NET Core in C#

By FoxLearn 6/5/2024 3:02:12 AM   5.74K
This post shows you How to Generate QR Code using ASP.NET Core in C#

Generating QR codes in C# ASP.NET Core using QRCoder is a straightforward process.

Here's a step-by-step guide:

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

c# qr coder

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# generate qr code in asp.net core

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