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

This post shows you How to Generate QR Code using ASP.NET Core in C#

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.

c# qr coder

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" />

Press F5 again, then change your url to QRCode/Index