How To Generate QR Code In ASP.NET MVC Core 6

Introduction

In this article, we will learn how to generate QR codes in ASP.NET MVC Core 6 by simply entering text, numbers, and a combination of both in the textbox and clicking on generate QR code button. I found a very useful library for generating QR codes which are IronBarcode. Download code and play with it.

You can install it through the NuGet package. It supports .Net Core, Standard & Framework. It has cross-platform support.

To use this library we will create a demo project in Visual Studio. I am creating ASP.NET Core Web App (Model-View-Controller). I am going to use the Visual Studio 2022 version.

Creating a New Project in Visual Studio

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View-Controller) > Next.

In the Configure your new project dialog, enter GenerateQRCode_Demo for the Project name. It's important to name the project GenerateQRCode_Demo. Capitalization needs to match each namespace when code is copied. Select Next.

In the Additional Information dialog, select .NET 6.0 (Long-term support). Select Create.

The Visual Studio project 2022 will now generate the structure for the selected application, and in this example, we are using ASP.Net MVC So we can create a controller to write the code or we can use the existing controller where you can enter the code and build/run the application.

Next, we can add the library to test the code.

How to Install the Barcode Library through NuGet Package Manager

The Visual Studio software provides the Nuget Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the Nuget Package Manager.

Search for the specific package IronBarcode using the search box on the upper left. Select a package from the list to display its information, enabling the Install button and a version-selection drop-down. As shown below screenshot. The NuGet package will be installed for your project and reference will be added. As in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.

Using the Visual Studio Command-Line

In Visual Studio, go to Tools-> Nuget Package Manager -> Package Manager Console

Enter the following line in the package manager console tab:

Install-Package IronBarCode

Now the package will download/install to the current project and be ready to use.

Add a class in the Models folder and write or copy-paste the below code.

using System.ComponentModel.DataAnnotations;
namespace GenerateQRCode_Demo.Models {
    public class GenerateQRCodeModel {
        [Display(Name = "Enter QR Code Text")]
        public string QRCodeText {
            get;
            set;
        }
    }
}

We will use exiting HomeController to write the code.

using GenerateQRCode_Demo.Models;
using IronBarCode;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Drawing;
namespace GenerateQRCode_Demo.Controllers {
    public class HomeController: Controller {
        private readonly IWebHostEnvironment _environment;
        public HomeController(IWebHostEnvironment environment) {
            _environment = environment;
        }
        public IActionResult CreateQRCode() {
                return View();
            }
            [HttpPost]
        public IActionResult CreateQRCode(GenerateQRCodeModel generateQRCode) {
            try {
                GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText, 200);
                barcode.AddBarcodeValueTextBelowBarcode();
                // Styling a QR code and adding annotation text
                barcode.SetMargins(10);
                barcode.ChangeBarCodeColor(Color.BlueViolet);
                string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
                if (!Directory.Exists(path)) {
                    Directory.CreateDirectory(path);
                }
                string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
                barcode.SaveAsPng(filePath);
                string fileName = Path.GetFileName(filePath);
                string imageUrl = $ "{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
                ViewBag.QrCodeUri = imageUrl;
            } catch (Exception) {
                throw;
            }
            return View();
        }
    }
}

Next "Add View" right-click on the CreateQRCode action method in HomeController class. Select "Add View" then select "Razor View" next click on the "Add" button.

  • In the View name CreateQRCode default name as action method in HomeController.

  • Template "Create"

  • In the Model, class drop-down, select GenerateQRCodeModel(GenerateQRCodeModel_Demo.Models).

  • Select Add.

Following is the CreateQRCode View code.

@model GenerateQRCode_Demo.Models.GenerateQRCodeModel

@{
    ViewData["Title"] = "CreateQRCode";
}
<h1>CreateQRCode</h1>
<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" />
      </div>
      <div class="form-group">
        <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
      </div>
    </form>
  </div>
</div>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Run project Ctrl+F5

Conclusion

Finally, we can create QR codes using the IronBarcode library. We can save QR codes as jpg, png images, Pdf, or HTML files. We can also add a logo to our QR code file. With its high-performance levels and a vast range of capabilities available to developers working with the Portable Document Format, we prefer IronBarcode. To know more about QR Code Generator in .NET. Click here