logo

,

Generate QR Code in Asp.net Core with 4 Simple Steps

In this article, we will see how to generate QR code in ASP.NET Core MVC project.

QR codes are two-dimensional barcodes that can be scanned by smartphones and other devices. QR codes can contain information such as URLs, text, or contact information.

Step 1 – Create an Asp.net Core MVC application.

You can give any name to this project. I will name it “MyQRCodeGenerator”.

I will remove all the Action Methods except Index Action Method from HomeController as I don’t need them for this example. My HomeController looks like below:

Step 2 – Edit Index View to Accept Input Data

Now, I will remove the existing code in the Index View of the Index Action Method. I will just add one input field to take the input data for generating the QR code. And, an image tag that will display the QR code once generated. Below is the code for the Index View.

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input type="text" name="inputData" />
<input type="submit" value="Generate QR Code" />
}

<br />

@if (ViewBag.QRCode != null)
{
<img src="@ViewBag.QRCode" style="width:200px; height:200px;" />
}

 

Step 3 – Add QRCoder nuget package

 

Step 4 – Add Post Action Method in HomeController

Now, I will add a post Action Method by name Index which will receive the input data and generate QR code for us.
Below is the code for the post action method for generating QR code.


        [HttpPost]
        public IActionResult Index(string inputData)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                QRCodeGenerator qRCodeGenerator = new QRCodeGenerator();
                QRCodeData qRCodeData = qRCodeGenerator.CreateQrCode(inputData, QRCodeGenerator.ECCLevel.Q);
                QRCode qRCode = new QRCode(qRCodeData);
                using(Bitmap bitmap = qRCode.GetGraphic(20))
                {
                    bitmap.Save(memoryStream, ImageFormat.Png);
                    ViewBag.QRCode = "data:image/png;base64," + Convert.ToBase64String(memoryStream.ToArray());
                }
            }

            return View();
        }

Step 5 – Demo

Don’t forget to check out Generate Barcode in Asp.net Core with 4 Simple Steps

Wrapping Up

QRCoder nuget package has made our job very easy. I hope, this blog post has helped you in learning and understanding on how to generate QR code in Asp.net Core. If you like it, share it with your friends and help this blog grow.

Don’t forget to check out What Happened to Startup.cs File in .Net 6?

6 Responses

Leave a Reply

Your email address will not be published.

Share on facebook
Share on twitter
Share on linkedin

Related articles