USING IRONQR

How to Scan QR Code in ASP .NET

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 an ASP.NET project using Visual Studio.
  2. Install IronQR library from the 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 QRCodeModel

// Import necessary namespaces
using System.ComponentModel.DataAnnotations;

namespace IronQRScannerAsp.Models
{
    public class QRCodeModel
    {
        // Property to hold the uploaded QR code image
        [Display(Name = "Select QR Image")]
        public IFormFile QRCodeImage { get; set; }
    }
}
// Import necessary namespaces
using System.ComponentModel.DataAnnotations;

namespace IronQRScannerAsp.Models
{
    public class QRCodeModel
    {
        // Property to hold the uploaded QR code image
        [Display(Name = "Select QR Image")]
        public IFormFile QRCodeImage { get; set; }
    }
}
' Import necessary namespaces
Imports System.ComponentModel.DataAnnotations

Namespace IronQRScannerAsp.Models
	Public Class QRCodeModel
		' Property to hold the uploaded QR code image
		<Display(Name := "Select QR Image")>
		Public Property QRCodeImage() As IFormFile
	End Class
End Namespace
$vbLabelText   $csharpLabel

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 the controller name.

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

Now add the following code to the controller.

// Import necessary namespaces
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;

namespace IronQRScannerAsp.Controllers
{
    // Controller to handle QR code scanning functionalities
    public class QrCodeController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        // Constructor for dependency injection of the hosting environment
        public QrCodeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        // Displays the initial View
        public IActionResult Index()
        {
            ViewBag.QrCodeText = "Text";
            return View();
        }

        // Handles the POST request to scan a QR code
        [HttpPost]
        public IActionResult ScanQRCode(QRCodeModel qrImage)
        {
            string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Define the file path for saving the uploaded QR image
            string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
            using (var stream = System.IO.File.Create(filePath))
            {
                qrImage.QRCodeImage.CopyTo(stream); // Save uploaded image to server
            }

            // 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 and get all embedded QR Codes
            IEnumerable<QrResult> results = reader.Read(imageInput);

            // Display scanned text and image on the view
            ViewBag.QrCodeText = results.First().Value;
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
            ViewBag.QrCodeUri = imageUrl;

            return View();
        }
    }
}
// Import necessary namespaces
using IronQr;
using IronQRScannerAsp.Models;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;

namespace IronQRScannerAsp.Controllers
{
    // Controller to handle QR code scanning functionalities
    public class QrCodeController : Controller
    {
        private readonly IWebHostEnvironment _environment;

        // Constructor for dependency injection of the hosting environment
        public QrCodeController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        // Displays the initial View
        public IActionResult Index()
        {
            ViewBag.QrCodeText = "Text";
            return View();
        }

        // Handles the POST request to scan a QR code
        [HttpPost]
        public IActionResult ScanQRCode(QRCodeModel qrImage)
        {
            string path = Path.Combine(_environment.WebRootPath, "ScanQRCode");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            // Define the file path for saving the uploaded QR image
            string filePath = Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png");
            using (var stream = System.IO.File.Create(filePath))
            {
                qrImage.QRCodeImage.CopyTo(stream); // Save uploaded image to server
            }

            // 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 and get all embedded QR Codes
            IEnumerable<QrResult> results = reader.Read(imageInput);

            // Display scanned text and image on the view
            ViewBag.QrCodeText = results.First().Value;
            string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/ScanQRCode/qrcode.png";
            ViewBag.QrCodeUri = imageUrl;

            return View();
        }
    }
}
' Import necessary namespaces
Imports IronQr
Imports IronQRScannerAsp.Models
Imports IronSoftware.Drawing
Imports Microsoft.AspNetCore.Mvc

Namespace IronQRScannerAsp.Controllers
	' Controller to handle QR code scanning functionalities
	Public Class QrCodeController
		Inherits Controller

		Private ReadOnly _environment As IWebHostEnvironment

		' Constructor for dependency injection of the hosting environment
		Public Sub New(ByVal environment As IWebHostEnvironment)
			_environment = environment
		End Sub

		' Displays the initial View
		Public Function Index() As IActionResult
			ViewBag.QrCodeText = "Text"
			Return View()
		End Function

		' Handles the POST request to scan a QR code
		<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

			' Define the file path for saving the uploaded QR image
			Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "ScanQRCode/qrcode.png")
			Using stream = System.IO.File.Create(filePath)
				qrImage.QRCodeImage.CopyTo(stream) ' Save uploaded image to server
			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 and get all embedded QR Codes
			Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)

			' Display scanned text and image on the view
			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
$vbLabelText   $csharpLabel

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 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 stores 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">
                <label for="QRCodeImage">Select QR Image:</label>
                <input asp-for="QRCodeImage" class="form-control" type="file" />
            </div>
            <div class="form-group">
                <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>
<div>
    <h3>Scanned Text:</h3>
    <h4>@ViewBag.QrCodeText</h4>
    @if (ViewBag.QrCodeUri != null)
    {
        <img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
    }
</div>
<div>
    <a asp-action="Index">Clear</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

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}")
$vbLabelText   $csharpLabel

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.

// Import necessary namespaces
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;

// Load an image file as a bitmap
var inputBmp = AnyBitmap.FromFile("QrImage.png");

// Use Auto => Machine Learning Scan
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
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);
// Import necessary namespaces
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
using System.Collections.Generic;

// Load an image file as a bitmap
var inputBmp = AnyBitmap.FromFile("QrImage.png");

// Use Auto => Machine Learning Scan
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
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);
' Import necessary namespaces
Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
Imports System.Collections.Generic

' Load an image file as a bitmap
Private inputBmp = AnyBitmap.FromFile("QrImage.png")

' Use Auto => Machine Learning Scan
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
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)
$vbLabelText   $csharpLabel

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.

Frequently Asked Questions

What is the purpose of integrating a QR code scanner in an ASP.NET application?

Integrating a QR code scanner in an ASP.NET application enhances user experience and functionality by allowing quick access to URLs, event ticket verification, payment facilitation, and providing additional product information using IronQR.

What library is recommended for QR code scanning in ASP.NET?

The recommended library for QR code scanning in ASP.NET is IronQR, which is a powerful .NET library designed for QR code generation and scanning.

How do you start creating a QR code scanner in ASP.NET?

To start creating a QR code scanner in ASP.NET, you need to create an ASP.NET project using Visual Studio, install the IronQR library from the Package Manager, and implement the necessary code to handle QR code scanning.

What image formats can IronQR read QR codes from?

IronQR can read QR codes from various image formats including jpg, png, svg, bmp, gif, tif, tiff, and multipage images.

Can IronQR handle different types of barcodes?

Yes, IronQR can handle a wide range of QR codes and other types of barcodes, including Micro QR codes, Aztec, and Data Matrix formats.

What platforms and project types does IronQR support?

IronQR supports various platforms and project types, including web (Blazor & WebForms), mobile (Xamarin & MAUI), desktop (WPF & MAUI), and console applications. It is compatible with C#, F#, and VB.NET.

How does IronQR enhance QR code reading accuracy?

IronQR enhances QR code reading accuracy by using an advanced Machine Learning Model for QR code recognition, ensuring reliable reading across various platforms.

How can developers acquire a trial license for IronQR?

Developers can obtain a trial license for IronQR from the Iron Software website. The license key needs to be placed in the appSettings.json file.

What are some key features of IronQR?

Key features of IronQR include reading and writing QR codes, error handling and correction, cross-platform compatibility, and broad support for various QR code and barcode formats.

Can IronQR read QR codes from video feeds?

Yes, IronQR can be modified to read QR codes from video feeds, enhancing its applicability in dynamic applications.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he says it’s one of his favorite aspects of working with Iron Software. Jordi grew up in Miami, Florida and studied Computer Science and Statistics at University of Florida.
< PREVIOUS
How to Generate QR Codes in ASP .NET Core
NEXT >
How to Scan QR Codes in C#

Ready to get started? Version: 2025.6 just released

View Licenses >