USING IRONQR

How to Scan QR Code in ASP .NET

Updated June 6, 2024
Share:

Introduction

QR codes have become ubiquitous in our digital world, frequently used in advertising, retail, event management, and more. For developers working in the ASP.NET framework, integrating QR code scanning capabilities into web applications can enhance user experience and functionality. This article explores the process of implementing a QR code scanner in an ASP.NET application, covering the required tools, libraries, and step-by-step implementation. We will use IronQR, a powerful library for QR code generation from Iron Software to read QR codes.

How to Scan QR Code in ASP .NET

  1. Create ASP.NET project using Visual Studio
  2. Install IronQR library from Package Manager
  3. Upload the QR Image and Read the QR.
  4. Read Advanced QR Code

Understanding QR Codes and Their Use Cases

QR (Quick Response) codes are two-dimensional barcodes that can store information ranging from URLs to contact details, typically scanned using smartphones or dedicated scanning devices. In web applications, QR codes can serve various purposes, such as:

  • Quick website access: Directing users to a specific URL without the need for typing.
  • Event ticketing: Verifying QR codes on tickets for event access.
  • Payment systems: Facilitating easy payment by scanning a QR code.
  • Product information: Providing additional information about products.

Introducing IronQR

IronQR is a powerful .NET library designed for QR code generation and scanning, providing robust functionality with ease of use in mind. This versatile library not only handles QR codes but can also manage other types of barcodes, making it a preferred choice for developers working within the .NET ecosystem. Here, we will explore how to integrate the IronQR library into an ASP.NET application to facilitate QR code scanning.

Key advantages and features of IronQR

  1. Reading QR Codes: IronQR can read QR codes from various image formats, including jpg, png, svg, bmp, gif, tif, tiff, and more. It also supports multipage images and custom QR detection models. Output data formats include text, URLs, coordinates, and more.
  2. Writing QR Codes: You can generate QR codes and save them as images (jpg, png, gif, tiff, bmp), streams, or even stamp them onto existing PDFs. Encode data such as text, URLs, bytes, and numbers and generate QR codes. Customize QR code styling by resizing, adjusting margins, recoloring, and adding logos.
  3. Error Handling and Correction: IronQR provides detailed error messages and custom QR error correction. It ensures fault tolerance and supports null checking and checksums.
  4. Advanced Machine Learning Model: IronQR uses an advanced Machine Learning Model for QR code recognition. This model ensures accurate and reliable QR code reading across various platforms, including mobile, desktop, and cloud environments.
  5. Cross-Platform Compatibility: IronQR is designed for C#, F#, and VB.NET, running on various .NET versions like .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), .NET Framework (4.6.2+)
  6. It supports different project types, including web (Blazor & WebForms), mobile (Xamarin & MAUI), desktop (WPF & MAUI), and console applications.
  7. Broad QR Code Support: IronQR excels in handling a wide range of QR codes and other types of barcodes. Whether you’re dealing with standard QR codes, Micro QR codes, a QR code barcode image, or even specific formats like Aztec or Data Matrix, IronQR has you covered. IronQR also supports the functionality to read QR code barcodes.

IronQR of .NET API products, which includes various tools for office documents, PDF editing, OCR, and more.

Step 1: Create a new ASP.NET project using Visual Studio

Start by creating a new Project and selecting the MVC template as shown below

How to Scan QR Code in ASP .NET: Figure 1 - Create a new ASP.NET project using Visual Studio

Next, you should provide a project name and location for the project.

How to Scan QR Code in ASP .NET: Figure 2 - Provide the project name and the location you wish to save.

Select .NET version.

How to Scan QR Code in ASP .NET: Figure 3 - Select the .NET version you wish to use.

Clicking the create button will create the following code and project.

How to Scan QR Code in ASP .NET: Figure 4 - Click the create button for Visual Studio to give you the template for your project

Step 2: Install IronQR library from the Visual Studio Package Manager

Install IronQR library from the Visual Studio package manager as shown below

How to Scan QR Code in ASP .NET: Figure 5 - Search for IronQR using the Visual Studio Package Manager and install it

IronQR can also be installed using NuGet Package Manager.

How to Scan QR Code in ASP .NET: Figure 6 - Search for IronQR via the NuGet Package Manager

Step 3: Upload the QR Image and Read QR Image

Now, let's create a QR code App.

Create QrCode Model

using System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
    public class QRCodeModel
    {
        [Display(Name = "Select QR Image")]
        public IFormFile QRCodeImage
        {
            get;
            set;
        }
    }
}
using System.ComponentModel.DataAnnotations;
namespace IronQRScannerAsp.Models
{
    public class QRCodeModel
    {
        [Display(Name = "Select QR Image")]
        public IFormFile QRCodeImage
        {
            get;
            set;
        }
    }
}
Imports System.ComponentModel.DataAnnotations
Namespace IronQRScannerAsp.Models
	Public Class QRCodeModel
		<Display(Name := "Select QR Image")>
		Public Property QRCodeImage() As IFormFile
	End Class
End Namespace
VB   C#

Create a QR Code Controller

Add a new controller, by right-clicking on the controller folder and providing a name shown below:

How to Scan QR Code in ASP .NET: Figure 7 - Add a new controller by clicking on the folder and give it a name

Select Empty Controller.

How to Scan QR Code in ASP .NET: Figure 8 - Click Empty Controller on the prompt

Provide controller name.

How to Scan QR Code in ASP .NET: Figure 9 - Name the controller

Now add the following code to the controller.

using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
    public class QrCodeController : Controller
    {
        private readonly IWebHostEnvironment _environment;
        public QrCodeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }
        public IActionResult Index()
        {
          ViewBag.QrCodeText = "Text";
          return View();
        }
        [HttpPost]
        public IActionResult ScanQRCode(QRCodeModel qrImage)
        {
            string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
            using (var stream = System.IO.File.Create(filePath))
            {
                qrImage.QRCodeImage.CopyTo(stream);
            }
            // Open the asset to read a QR Code from
            var bitmap = AnyBitmap.FromFile(filePath);
            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(bitmap);
            // Create a QR Reader object
            QrReader reader = new QrReader();
            // Read the Input an get all embedded QR Codes
            IEnumerable<QrResult> results = reader.Read(imageInput);
            ViewBag.QrCodeText = results.First().Value;
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
            ViewBag.QrCodeUri = imageUrl;
          return View();
        }
    }
}
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace IronQRScannerAsp.Controllers
{
    public class QrCodeController : Controller
    {
        private readonly IWebHostEnvironment _environment;
        public QrCodeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }
        public IActionResult Index()
        {
          ViewBag.QrCodeText = "Text";
          return View();
        }
        [HttpPost]
        public IActionResult ScanQRCode(QRCodeModel qrImage)
        {
            string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
            using (var stream = System.IO.File.Create(filePath))
            {
                qrImage.QRCodeImage.CopyTo(stream);
            }
            // Open the asset to read a QR Code from
            var bitmap = AnyBitmap.FromFile(filePath);
            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(bitmap);
            // Create a QR Reader object
            QrReader reader = new QrReader();
            // Read the Input an get all embedded QR Codes
            IEnumerable<QrResult> results = reader.Read(imageInput);
            ViewBag.QrCodeText = results.First().Value;
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
            ViewBag.QrCodeUri = imageUrl;
          return View();
        }
    }
}
Imports IronQr
Imports IronQRScannerAsp.Models
Imports IronSoftware.Drawing
Imports Microsoft.AspNetCore.Mvc
Namespace IronQRScannerAsp.Controllers
	Public Class QrCodeController
		Inherits Controller

		Private ReadOnly _environment As IWebHostEnvironment
		Public Sub New(ByVal environment As IWebHostEnvironment)
			_environment = environment
		End Sub
		Public Function Index() As IActionResult
		  ViewBag.QrCodeText = "Text"
		  Return View()
		End Function
		<HttpPost>
		Public Function ScanQRCode(ByVal qrImage As QRCodeModel) As IActionResult
			Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode")
			If Not Directory.Exists(path) Then
				Directory.CreateDirectory(path)
			End If
			Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png")
			Using stream = System.IO.File.Create(filePath)
				qrImage.QRCodeImage.CopyTo(stream)
			End Using
			' Open the asset to read a QR Code from
			Dim bitmap = AnyBitmap.FromFile(filePath)
			' Load the asset into QrImageInput
			Dim imageInput As New QrImageInput(bitmap)
			' Create a QR Reader object
			Dim reader As New QrReader()
			' Read the Input an get all embedded QR Codes
			Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)
			ViewBag.QrCodeText = results.First().Value
			Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}" & "/ScanQRCode/qrcode.png"
			ViewBag.QrCodeUri = imageUrl
		  Return View()
		End Function
	End Class
End Namespace
VB   C#

Code Explanation

The provided code snippet is for an ASP.NET Core MVC controller named QrCodeController, which is designed to handle QR code scanning functionalities using the IronQR library. Here's a brief description of what the code does:

1. Saving the Uploaded QR Code Image

Path Construction

It constructs a file path (path) within the application's web root directory specifically for saving QR code images ("ScanQRCode" directory).

It checks if this directory exists, and if not, creates it to avoid any file not found errors when saving the file.

File Saving

It constructs the full file path (filePath) where the uploaded QR code image will be saved ("ScanQRCode/qrcode.png"). This overwrites any existing file with the same name, effectively handling new scans without accumulating files.

It opens a file stream and copies the content of the uploaded image (qrImage.QRCodeImage, likely a form file) to the specified location on the server.

2. Decoding the QR Code

Reading the Image File

Utilizes AnyBitmap.FromFile(filePath) to load the saved image file into a format suitable for QR code scanning. AnyBitmap likely serves as a helper class for converting image files into a bitmap object that the QR reader can process.

Initializing the QR Reader

Wraps the loaded bitmap into a QrImageInput, which is specifically designed to be an input for the QR code reading process. Instantiates a QrReader, a component of the IronQR library configured to detect and decode QR codes.

Scanning the QR Code

Calls reader.Read(imageInput) to scan the image for QR codes. This method returns an IEnumerable<QrResult>, where each QrResult contains data from a detected QR code in the image. It extracts the first result's value using results.First().Value and store this decoded information in ViewBag.QrCodeText. This assumes the image contains at least one QR code and does not handle potential errors where no QR codes are detected.

3. Preparing and Returning the Response

Image URL Construction

Constructs a URL (imageUrl) pointing to the saved QR code image on the server. This URL is constructed using the current HTTP request's scheme, host, and path base, ensuring it's accessible to users for viewing. The constructed URL is saved in ViewBag.QrCodeUri.

View Return

Returns the same view (View()), which likely displays both the QR code image and the decoded text to the user. The ViewBag is used to pass the QR code's decoded text and the URL of the image to the view for rendering.

Add View to the Controller class

Add a new view, right-click on the CreateQRCode action method in the QrCodeController class.

How to Scan QR Code in ASP .NET: Figure 10 - Add a new view in the `QrCodeController` class

Select the option "Add View" then select "Razor View". Click on "Add".

How to Scan QR Code in ASP .NET: Figure 11 - Select the Add View option, then Razor View, then Add

Then select the "Create" template and Model class generated previously.

How to Scan QR Code in ASP .NET: Figure 12 - Select the Create template generated previously

Now replace the code in the view class with the one shown below.

@model IronQRScannerAsp.Models.QRCodeModel
@{
    ViewData["Title"] = "ScanQRCode";
}
<h1>ScanQRCode</h1>
<h4>QRCodeModel</h4>
<hr />
<div class="row">
    <div class="col-md-14">
        <form asp-action="ScanQRCode" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
            </div>
            <div class="form-group">
                <h3>Scanned Text:</h3>
                <h4>@ViewBag.QrCodeText</h4>
            </div>
            <div class="form-group">
                <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
            </div>
        </form>
    </div>
</div>
<div>
    <a asp-action="Index">Clear</a>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}
@model IronQRScannerAsp.Models.QRCodeModel
@{
    ViewData["Title"] = "ScanQRCode";
}
<h1>ScanQRCode</h1>
<h4>QRCodeModel</h4>
<hr />
<div class="row">
    <div class="col-md-14">
        <form asp-action="ScanQRCode" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
            </div>
            <div class="form-group">
                <h3>Scanned Text:</h3>
                <h4>@ViewBag.QrCodeText</h4>
            </div>
            <div class="form-group">
                <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
            </div>
        </form>
    </div>
</div>
<div>
    <a asp-action="Index">Clear</a>
</div>
@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}
model ReadOnly Property () As IronQRScannerAsp.Models.QRCodeModel
	ViewData("Title") = "ScanQRCode"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> </div> <div class="form-group"> <h3> Scanned Text:</h3> <h4> @ViewBag.QrCodeText</h4> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> <div> <a asp-action="Index"> Clear</a> </div> @section Scripts
"form-group"> </div> <div class="form-group"> (Of h3) Scanned Text
	Inherits </h3>(Of h4) ViewBag.QrCodeText</h4> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> (Of div) <a asp-action="Index"> Clear</a> </div> section Scripts

'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> </div> <div class
"text-danger"></div> <div class="form-group"> </div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class
"ModelOnly" class="text-danger"></div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary="ModelOnly" class
"multipart/form-data"> <div asp-validation-summary="ModelOnly" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary
"ScanQRCode" enctype="multipart/form-data"> <div asp-validation-summary
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action="ScanQRCode" enctype
"col-md-14"> <form asp-action="ScanQRCode" enctype
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Friend <h1> ScanQRCode</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-14"> <form asp-action
"row"> <div class="col-md-14"> <form asp-action
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Private Private Private Private Private Private Private Friend (Of h1) ScanQRCode</h1> (Of h4) QRCodeModel</h4> <hr /> <div Class="row"> <div class
	@
	If True Then
		Await Html.RenderPartialAsync("_ValidationScriptsPartial")
	End If
End Class
VB   C#

Now in the program.cs change the following code to make the above view as the default route

app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}");
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}");
app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=Index}")
VB   C#

This changes the default route from HomeController to our QrCode Controller.

Input Image with URL: https://ironsoftware.com/csharp/qr.

How to Scan QR Code in ASP .NET: Figure 13 - Example QR code input

Output

How to Scan QR Code in ASP .NET: Figure 14 - Example Output after following the steps from above

On the page, select a QR code image and click upload to decode the QR code. This app can also be modified to read from a Video feed and display results.

Step 4: Read Advanced QR Code

To read advanced QR codes, IronQR provides the following settings.

using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
// Careful Scan => Useful for scanning documents slowly and carefully
QrImageInput scan_ML_and_normal = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results1 = new QrReader().Read(scan_ML_and_normal);
// Use Machine Learning Scan
// High Speed => For scanning frames from a camera
QrImageInput scan_ML_only = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results2 = new QrReader().Read(scan_ML_only);
// Use Scan without Machine Learning
QrImageInput scan_normal_only = new QrImageInput(inputBmp, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> results3 = new QrReader().Read(scan_normal_only);
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;
var inputBmp = AnyBitmap.FromFile("QrImage.png");
// Use Auto => Machine Learning Scan
// Careful Scan => Useful for scanning documents slowly and carefully
QrImageInput scan_ML_and_normal = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results1 = new QrReader().Read(scan_ML_and_normal);
// Use Machine Learning Scan
// High Speed => For scanning frames from a camera
QrImageInput scan_ML_only = new QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel);
IEnumerable<QrResult> results2 = new QrReader().Read(scan_ML_only);
// Use Scan without Machine Learning
QrImageInput scan_normal_only = new QrImageInput(inputBmp, QrScanMode.OnlyBasicScan);
IEnumerable<QrResult> results3 = new QrReader().Read(scan_normal_only);
Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
Imports System.Collections.Generic
Private inputBmp = AnyBitmap.FromFile("QrImage.png")
' Use Auto => Machine Learning Scan
' Careful Scan => Useful for scanning documents slowly and carefully
Private scan_ML_and_normal As New QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel)
Private results1 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_ML_and_normal)
' Use Machine Learning Scan
' High Speed => For scanning frames from a camera
Private scan_ML_only As New QrImageInput(inputBmp, QrScanMode.OnlyDetectionModel)
Private results2 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_ML_only)
' Use Scan without Machine Learning
Private scan_normal_only As New QrImageInput(inputBmp, QrScanMode.OnlyBasicScan)
Private results3 As IEnumerable(Of QrResult) = (New QrReader()).Read(scan_normal_only)
VB   C#

By leveraging the latest in ML technology, we have elevated the QR code reader to new heights. The sophisticated ML model enhances the accuracy and efficiency of applications in decoding QR codes, even under complex conditions. Whether reading QR codes from still images, video streams, or live camera feeds, the ML-powered solution delivers the required information quickly and reliably. This innovation streamlines data retrieval and boosts security by identifying genuine QR codes and flagging potential threats. With our ML technology, you can be confident that your QR code scanning capabilities are at the cutting edge, providing your users with a smooth and secure experience

License (Trial Available)

Developers can get an IronQR trial license from here. The Key needs to be placed in the appSettings.json.

{
  "IronQR.License.LicenseKey": "My key"
}

Conclusion

In this article, we've explored how to scan QR codes in ASP.NET Core using IronQR. Integrating IronQR into an ASP.NET application for QR code scanning is a straightforward process that enhances the capabilities of web applications, making them more interactive and user-friendly. IronQR's powerful features and ease of use make it an excellent choice for developers looking to implement barcode-related functionalities.

< PREVIOUS
How to Generate QR Codes in ASP .NET Core
NEXT >
How to Scan QR Codes in C#

Ready to get started? Version: 2024.6 just released

Start Free Trial Total downloads: 8,630
View Licenses >