Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
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:
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.
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.
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.
Error Handling and Correction: IronQR provides detailed error messages and custom QR error correction. It ensures fault tolerance and supports null checking and checksums.
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.
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+).
It supports different project types, including web (Blazor & WebForms), mobile (Xamarin & MAUI), desktop (WPF & MAUI), and console applications.
IronQR of .NET API products, which includes various tools for office documents, PDF editing, OCR, and more.
Start by creating a new Project and selecting the MVC template as shown below:
Next, you should provide a project name and location for the project.
Select .NET version.
Clicking the create button will create the following code and project.
Install IronQR library from the Visual Studio package manager as shown below:
IronQR can also be installed using NuGet Package Manager.
Now, let's create a QR code App.
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
Add a new controller, by right-clicking on the controller folder and providing a name shown below:
Select Empty Controller.
Provide the controller name.
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
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:
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.qrImage.QRCodeImage
, likely a form file) to the specified location on the server.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.QrImageInput
, which is specifically designed to be an input for the QR code reading process.QrReader
, a component of the IronQR library configured to detect and decode QR codes.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.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.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.ViewBag.QrCodeUri
.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 a new view, right-click on the CreateQRCode
action method in the QrCodeController
class.
Select the option "Add View" then select "Razor View". Click on "Add".
Then select the "Create" template and Model class 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}")
This changes the default route from HomeController
to our QrCode
Controller.
Input Image with URL: https://ironsoftware.com/csharp/qr/.
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.
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)
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
Developers can get an IronQR trial license from here. The Key needs to be placed in the appSettings.json
.
{
"IronQR.License.LicenseKey": "My Key"
}
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.
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.
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.
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.
IronQR can read QR codes from various image formats including jpg, png, svg, bmp, gif, tif, tiff, and multipage images.
Yes, IronQR can handle a wide range of QR codes and other types of barcodes, including Micro QR codes, Aztec, and Data Matrix formats.
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.
IronQR enhances QR code reading accuracy by using an advanced Machine Learning Model for QR code recognition, ensuring reliable reading across various platforms.
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.
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.
Yes, IronQR can be modified to read QR codes from video feeds, enhancing its applicability in dynamic applications.