Creating QR Code In ASP.NET Core

Background

Now a day's QR (Quick response) code becomes the internal part of our digital life. We will see a QR code on any E-tickets such as Stadium, air, bus, hotel booking. One of the best examples is India's UPI payment which is initiated by Indian PM Narendra Modi. You just have to scan the QR code to make the payment digital to the person’s bank account. This initiative is the very game changer since all the money comes to the bank and helped to stop the black money.

There are also many businesses generating the bar codes on E-Receipts to validate the authenticity of the receipt which can give the assurance that it's not been manipulated, which people did in the past simply editing and making false documents. There are many benefits using the QR code, the typical QR code will look like as follows.

QR Code In ASP.NET Core

Now in this article, we will learn how to generate a QR code using ASP.NET Core MVC. Let's learn step by step by creating an ASP.NET Core application.

Step 1. Create ASP.NET Core MVC Application

  • Start then All Programs and select "Microsoft Visual Studio 2019".
  • Once the Visual Studio Opens, Then click on Continue Without Code.
  • Then Go to Visual Studio Menu, click on File => New Project then choose ASP.NET Core Web App (Model-View-Controller) Project Template.
  • Then define the project name, location of the project, Target Framework, then click on the create button.

The preceding steps will create the ASP.NET Core MVC application and solution explorer. It will look like as shown in the following image.

QR Code In ASP.NET Core

Delete the existing auto-generated code including controller and views for ease of understanding. We will add step by step while building the application.

Step 2. Add QRCoder Nuget Package Reference

The QRCoder is the open source pure C# library to generate the codes. The QRCoder supports the basic to custom and complex OR code generation, follow the following steps to add the Nuget package.

  • Right click on the Solution Explorer, find Manage NuGet Package Manager and click on it
  • After as shown into the image and type in search box "QRCoder"
  • Select QRCoder as shown into the image
  • Choose version of QRCoder library and click on install button

QR Code In ASP.NET Core

I hope you have followed the same steps and installed the QRCoder nuget package.

Step 3. Create the Model Class

Create the model class QRCodeModel by right clicking on the model folder to take the input text for QR code as shown in the following image.

QR Code In ASP.NET Core

Now open the QRCodeModel.cs class file and add the following code.

using System.ComponentModel.DataAnnotations;

namespace GeneratingQRCode.Models
{
    public class QRCodeModel
    {
        [Display(Name = "Enter QRCode Text")]
        public string QRCodeText { get; set; }

    }
}

Step 4. Add the Controller

Create the Controller class by right clicking on the Controller folder as shown in the following image.

QR Code In ASP.NET Core

Now open the HomeController.cs file and add the following code.

using GeneratingQRCode.Models;
using Microsoft.AspNetCore.Mvc;
using QRCoder;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace GeneratingQRCode.Controllers
{
    public class HomeController : Controller
    {

        [HttpGet]
        public IActionResult CreateQRCode()
        {
            return View();
        }

        [HttpPost]
        public IActionResult CreateQRCode(QRCodeModel qRCode)
        {
            QRCodeGenerator QrGenerator = new QRCodeGenerator();
            QRCodeData QrCodeInfo = QrGenerator.CreateQrCode(qRCode.QRCodeText, QRCodeGenerator.ECCLevel.Q);
            QRCode QrCode = new QRCode(QrCodeInfo);
            Bitmap QrBitmap = QrCode.GetGraphic(60);  
            byte[] BitmapArray = QrBitmap.BitmapToByteArray();
            string QrUri = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(BitmapArray));
            ViewBag.QrCodeUri = QrUri;
            return View();
        }
    }

    //Extension method to convert Bitmap to Byte Array
    public static class BitmapExtension
    {
        public static byte[] BitmapToByteArray(this Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
    }
}

Step 5. Create The View

Create the view with the name CreateQRCode using the model class QRCodeModel by right clicking on the view folder or right clicking in the controller class file as shown in the following image.

QR Code In ASP.NET Core

After clicking the Add button, it generates the view with the name CreateQRCode. Now open the CreateQRCode.cshtml file and replace the default generated code as follows.

CreateQRCode.cshtml

@model GeneratingQRCode.Models.QRCodeModel

@{
    ViewData["Title"] = "www.compilemode.com";
}
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="CreateQRCode">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="QRCodeText" class="control-label"></label>
                <input asp-for="QRCodeText" class="form-control" />
                <span asp-validation-for="QRCodeText" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Generate QR Code" class="btn btn-primary text-center" />
            </div>
            <div class="form-group">

                <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
            </div>
        </form>
    </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

In the preceding code you see the image tag src Uri assigned with ViewBag, which we have set from the HomeController class.

Step 6. Configure the Routing

We have modified the auto-generated files, so we have to set the default routing so that when you run the application, then the default view can start in the browser. Now open the Startup.cs and set the default routing as per our controller and the created view as shown in the following image.

QR Code In ASP.NET Core

After adding all the required files and configuration, the Solution explorer of our created ASP.NET core application will look like as follows.

QR Code In ASP.NET Core

Step 7. Run the Application

Now press Keyboard F5 or Visual Studio run button to run the application. After running the application, the following screen will be shown in the browser. Enter the QR code text and click on the Generate QR code button, then it will generate the following code as in the following screenshot.

QR Code In ASP.NET Core

Demo

QR Code In ASP.NET Core

Step 8. Read the QR Code

Open your mobile phone QR code reader application and scan it, it will show the following text which we have entered during the QR code creation.

QR Code In ASP.NET Core

Summary

I hope, from all the above examples, you have learned how to generate a QR code using the ASP.NET Core. If you like it, share it with your friends, subscribe to the blog and YouTube channel for more such articles.

Related Articles


Similar Articles