How To Generate QR Code Using ASP.NET Core

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.


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 1: 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

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

Step 2: 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.


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 3: Add the Controller

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


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 4: 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.


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 5: 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.


Step 6: 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.

Demo


Step 7: Read the QR Code

Open the 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.




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.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compilemode