ASP.NET Core Barcode Scanner

Introduction

ASP.NET Core is a cross-platform framework for building modern web applications. Its Razor Pages model offers a page-based approach to handling HTTP requests, which makes it well suited for server-side barcode processing. With IronBarcode, uploaded images can be received as IFormFile objects, converted to byte arrays, and passed directly to the barcode reader without writing temporary files to disk.

This article walks through integrating IronBarcode into an ASP.NET Core Razor Pages application to scan barcodes and QR codes from uploaded images, as well as generate barcodes from the server.

IronBarcode: C# Barcode Library

IronBarcode provides a robust API for reading and writing barcodes in .NET applications. The library handles image processing internally, so developers can pass raw bytes, file paths, or streams directly to the BarcodeReader.Read method without needing separate image processing libraries. It supports a wide range of barcode formats including QR Code, Code 128, Code 39, PDF417, EAN, and many others.

For web applications, IronBarcode is particularly useful because it processes images entirely in memory. Uploaded files never need to be saved to disk, which simplifies deployment and reduces cleanup overhead. The same library also generates barcodes with BarcodeWriter.CreateBarcode, making it a single dependency for both reading and writing.

Steps to Build a Barcode Scanner in ASP.NET Core

Follow these steps to create a web-based barcode scanner using ASP.NET Core Razor Pages and IronBarcode.

Prerequisites

  1. Visual Studio 2022 or later (or any IDE with .NET support)
  2. .NET 6.0 or later SDK

Create the Project

Create a new ASP.NET Core Web App (Razor Pages) project. This can be done through Visual Studio's project wizard or from the command line:

dotnet new webapp -n BarcodeWebApp
dotnet new webapp -n BarcodeWebApp
SHELL

Install IronBarcode Library

Install the IronBarcode library using the NuGet Package Manager Console. Navigate to Tools > NuGet Package Manager > Package Manager Console in Visual Studio and run:

Install-Package BarCode

Alternatively, install it from the command line with dotnet add package BarCode. The latest version is available on the NuGet website.

Frontend

The frontend consists of a file upload form and a result display area. The form uses enctype="multipart/form-data" to handle binary file uploads. When a barcode is detected, the result appears in a success alert below the uploaded image.

Replace the content in the Index.cshtml file with the following:

@page
@model IndexModel
@{
    ViewData["Title"] = "Barcode Scanner";
}

<div class="container mt-4">
    <h1 class="mb-4">Barcode Scanner</h1>

    <div class="card mb-4">
        <div class="card-header"><h5>Upload & Read Barcode</h5></div>
        <div class="card-body">
            <form method="post" asp-page-handler="Upload" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="file" class="form-label">Select a barcode image:</label>
                    <input type="file" class="form-control" id="file"
                           name="UploadedFile" accept="image/*" />
                </div>
                <button type="submit" class="btn btn-primary">Scan Barcode</button>
            </form>

            @if (Model.ImageDataUrl != null)
            {
                <div class="mt-3">
                    <h6>Uploaded Image:</h6>
                    <img src="@Model.ImageDataUrl" alt="Uploaded barcode"
                         style="max-width: 300px;" class="img-thumbnail" />
                </div>
            }

            @if (Model.BarcodeResult != null)
            {
                <div class="alert alert-success mt-3">
                    <strong>Barcode Value:</strong> @Model.BarcodeResult
                </div>
            }

            @if (Model.ErrorMessage != null)
            {
                <div class="alert alert-warning mt-3">@Model.ErrorMessage</div>
            }
        </div>
    </div>
</div>
@page
@model IndexModel
@{
    ViewData["Title"] = "Barcode Scanner";
}

<div class="container mt-4">
    <h1 class="mb-4">Barcode Scanner</h1>

    <div class="card mb-4">
        <div class="card-header"><h5>Upload & Read Barcode</h5></div>
        <div class="card-body">
            <form method="post" asp-page-handler="Upload" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="file" class="form-label">Select a barcode image:</label>
                    <input type="file" class="form-control" id="file"
                           name="UploadedFile" accept="image/*" />
                </div>
                <button type="submit" class="btn btn-primary">Scan Barcode</button>
            </form>

            @if (Model.ImageDataUrl != null)
            {
                <div class="mt-3">
                    <h6>Uploaded Image:</h6>
                    <img src="@Model.ImageDataUrl" alt="Uploaded barcode"
                         style="max-width: 300px;" class="img-thumbnail" />
                </div>
            }

            @if (Model.BarcodeResult != null)
            {
                <div class="alert alert-success mt-3">
                    <strong>Barcode Value:</strong> @Model.BarcodeResult
                </div>
            }

            @if (Model.ErrorMessage != null)
            {
                <div class="alert alert-warning mt-3">@Model.ErrorMessage</div>
            }
        </div>
    </div>
</div>
HTML

The layout uses Bootstrap classes already included in the default ASP.NET Core template. The form submits to the Upload page handler, and conditional blocks display the uploaded image preview, the decoded result, or an error message.

Sample Input Barcodes

The following sample barcodes can be used to test the scanner. Each image encodes a different format and value:

ASP.NET Core Barcode Scanner - Sample QR Code input encoding a URL

QR Code encoding "https://ironsoftware.com"

ASP.NET Core Barcode Scanner - Sample Code 128 barcode input

Code 128 barcode encoding "IRONBARCODE-2026"

ASP.NET Core Barcode Scanner - Sample Code 39 barcode input

Code 39 barcode encoding "HELLO123"

Barcode Scanning with IronBarcode

The server-side logic handles the uploaded file in the OnPostUploadAsync method. The uploaded IFormFile is read into a byte array, which is passed directly to BarcodeReader.Read. This avoids saving temporary files and keeps the processing entirely in memory.

Replace the content in Index.cshtml.cs with:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using IronBarCode;

public class IndexModel : PageModel
{
    [BindProperty]
    public IFormFile? UploadedFile { get; set; }

    public string? BarcodeResult { get; set; }
    public string? ErrorMessage { get; set; }
    public string? ImageDataUrl { get; set; }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPostUploadAsync()
    {
        if (UploadedFile == null || UploadedFile.Length == 0)
        {
            ErrorMessage = "Please select an image file.";
            return Page();
        }

        try
        {
            using var ms = new MemoryStream();
            await UploadedFile.CopyToAsync(ms);
            byte[] imageBytes = ms.ToArray();

            // Store image as base64 for preview display
            string base64 = Convert.ToBase64String(imageBytes);
            ImageDataUrl = $"data:{UploadedFile.ContentType};base64,{base64}";

            // Read barcode from uploaded image bytes
            var results = BarcodeReader.Read(imageBytes);

            if (results != null && results.Count() > 0)
            {
                BarcodeResult = string.Join("\n",
                    results.Select(r => r.Value));
            }
            else
            {
                ErrorMessage = "No barcode detected in the uploaded image.";
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Error processing image: {ex.Message}";
        }

        return Page();
    }
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using IronBarCode;

public class IndexModel : PageModel
{
    [BindProperty]
    public IFormFile? UploadedFile { get; set; }

    public string? BarcodeResult { get; set; }
    public string? ErrorMessage { get; set; }
    public string? ImageDataUrl { get; set; }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPostUploadAsync()
    {
        if (UploadedFile == null || UploadedFile.Length == 0)
        {
            ErrorMessage = "Please select an image file.";
            return Page();
        }

        try
        {
            using var ms = new MemoryStream();
            await UploadedFile.CopyToAsync(ms);
            byte[] imageBytes = ms.ToArray();

            // Store image as base64 for preview display
            string base64 = Convert.ToBase64String(imageBytes);
            ImageDataUrl = $"data:{UploadedFile.ContentType};base64,{base64}";

            // Read barcode from uploaded image bytes
            var results = BarcodeReader.Read(imageBytes);

            if (results != null && results.Count() > 0)
            {
                BarcodeResult = string.Join("\n",
                    results.Select(r => r.Value));
            }
            else
            {
                ErrorMessage = "No barcode detected in the uploaded image.";
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = $"Error processing image: {ex.Message}";
        }

        return Page();
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports Microsoft.AspNetCore.Mvc.RazorPages
Imports IronBarCode
Imports System.IO
Imports System.Threading.Tasks

Public Class IndexModel
    Inherits PageModel

    <BindProperty>
    Public Property UploadedFile As IFormFile

    Public Property BarcodeResult As String
    Public Property ErrorMessage As String
    Public Property ImageDataUrl As String

    Public Sub OnGet()
    End Sub

    Public Async Function OnPostUploadAsync() As Task(Of IActionResult)
        If UploadedFile Is Nothing OrElse UploadedFile.Length = 0 Then
            ErrorMessage = "Please select an image file."
            Return Page()
        End If

        Try
            Using ms As New MemoryStream()
                Await UploadedFile.CopyToAsync(ms)
                Dim imageBytes As Byte() = ms.ToArray()

                ' Store image as base64 for preview display
                Dim base64 As String = Convert.ToBase64String(imageBytes)
                ImageDataUrl = $"data:{UploadedFile.ContentType};base64,{base64}"

                ' Read barcode from uploaded image bytes
                Dim results = BarcodeReader.Read(imageBytes)

                If results IsNot Nothing AndAlso results.Count() > 0 Then
                    BarcodeResult = String.Join(vbLf, results.Select(Function(r) r.Value))
                Else
                    ErrorMessage = "No barcode detected in the uploaded image."
                End If
            End Using
        Catch ex As Exception
            ErrorMessage = $"Error processing image: {ex.Message}"
        End Try

        Return Page()
    End Function
End Class
$vbLabelText   $csharpLabel

The key steps in the code above:

  1. Receive the upload - The IFormFile is bound via [BindProperty] and received in the POST handler.
  2. Convert to bytes - The file is copied to a MemoryStream and converted to a byte array. This is the same approach used in the web scanner example, adapted for ASP.NET Core's IFormFile instead of base64 strings.
  3. Read the barcode - BarcodeReader.Read(imageBytes) processes the image and returns all detected barcodes.
  4. Display the result - All detected barcode values are joined and displayed in the UI.

The following GIF demonstrates the barcode reader in action, uploading a barcode image and displaying the decoded result:

ASP.NET Core Barcode Scanner - Demonstration of uploading and reading a barcode

Barcode reader scanning an uploaded image in the ASP.NET Core application

Processing Base64 Image Data

For applications that receive image data as base64 strings (e.g., from webcam captures or JavaScript canvas), the same BarcodeReader.Read method works with byte arrays decoded from base64. This pattern is common in single-page applications that send image data via AJAX:

public string ReadBarCode(string imageDataBase64)
{
    // Decode the base64 image data
    var splitObject = imageDataBase64.Split(',');
    byte[] imageByteData = Convert.FromBase64String(
        (splitObject.Length > 1) ? splitObject[1] : splitObject[0]);

    // Read barcode directly from byte array
    var results = BarcodeReader.Read(imageByteData);

    return $"{DateTime.Now}: Barcode is ({results.First().Value})";
}
public string ReadBarCode(string imageDataBase64)
{
    // Decode the base64 image data
    var splitObject = imageDataBase64.Split(',');
    byte[] imageByteData = Convert.FromBase64String(
        (splitObject.Length > 1) ? splitObject[1] : splitObject[0]);

    // Read barcode directly from byte array
    var results = BarcodeReader.Read(imageByteData);

    return $"{DateTime.Now}: Barcode is ({results.First().Value})";
}
Public Function ReadBarCode(imageDataBase64 As String) As String
    ' Decode the base64 image data
    Dim splitObject = imageDataBase64.Split(","c)
    Dim imageByteData As Byte() = Convert.FromBase64String(
        If(splitObject.Length > 1, splitObject(1), splitObject(0)))

    ' Read barcode directly from byte array
    Dim results = BarcodeReader.Read(imageByteData)

    Return $"{DateTime.Now}: Barcode is ({results.First().Value})"
End Function
$vbLabelText   $csharpLabel

This approach handles both raw base64 and data URI formats (e.g., data:image/png;base64,...) by splitting on the comma and taking the actual base64 payload. For a complete Blazor implementation using this pattern, see the Blazor integration guide.

Generating Barcodes on the Server

IronBarcode can also generate barcodes server-side. Adding a generation endpoint to the same application is straightforward with BarcodeWriter.CreateBarcode:

public IActionResult OnPostGenerate()
{
    var barcode = BarcodeWriter.CreateBarcode(
        "https://ironsoftware.com", BarcodeEncoding.QRCode);
    byte[] barcodeBytes = barcode.ToPngBinaryData();

    return File(barcodeBytes, "image/png", "generated-barcode.png");
}
public IActionResult OnPostGenerate()
{
    var barcode = BarcodeWriter.CreateBarcode(
        "https://ironsoftware.com", BarcodeEncoding.QRCode);
    byte[] barcodeBytes = barcode.ToPngBinaryData();

    return File(barcodeBytes, "image/png", "generated-barcode.png");
}
Public Function OnPostGenerate() As IActionResult
    Dim barcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com", BarcodeEncoding.QRCode)
    Dim barcodeBytes As Byte() = barcode.ToPngBinaryData()

    Return File(barcodeBytes, "image/png", "generated-barcode.png")
End Function
$vbLabelText   $csharpLabel

The generated barcode is returned as a file download. The following image shows the QR code output produced by the OnPostGenerate handler:

ASP.NET Core Barcode Scanner - Server-generated QR code output

QR code generated server-side with BarcodeWriter.CreateBarcode

For more barcode generation options, see the barcode image generation tutorial and the barcode styling guide.

Running the Application

Run the project from Visual Studio or the command line:

dotnet run
dotnet run
SHELL

The application starts on the port specified in launchSettings.json (typically https://localhost:5001 or similar). Navigate to the home page to see the barcode scanner interface.

Conclusion

This article demonstrated how to build a server-side barcode scanner using ASP.NET Core Razor Pages and IronBarcode. The same approach works with ASP.NET Core MVC controllers, Web API endpoints, and Blazor Server applications by adapting how the image data is received. IronBarcode handles the image processing internally, so the integration requires minimal code regardless of the web framework.

For reading barcodes in other .NET platforms, see the .NET MAUI barcode scanner tutorial and the barcode reading how-to guides. Get more tutorials on IronBarcode from the reading barcodes tutorial.

To get started quickly, download the complete BarcodeWebApp project and run it with dotnet run.

IronBarcode must be licensed for development and commercial use. Licensing details are available here.

Frequently Asked Questions

How can I implement a barcode scanner in ASP.NET Core using Razor Pages?

You can use IronBarcode in your ASP.NET Core Razor Pages project to implement a barcode scanner. The library allows you to read various barcode formats, such as QR Codes, Code 128, and Code 39, by uploading images and processing them with BarcodeReader.Read.

What types of barcodes can be read using IronBarcode?

IronBarcode supports reading multiple barcode formats including QR Codes, Code 128, and Code 39, making it versatile for various applications.

How do I upload images for barcode scanning in an ASP.NET Core project?

In an ASP.NET Core project, you can upload images using IFormFile. IronBarcode processes these images to read the barcodes contained within them.

Can IronBarcode generate barcodes server-side in ASP.NET Core?

Yes, IronBarcode can generate barcodes server-side in ASP.NET Core using the BarcodeWriter.CreateBarcode method, allowing you to create and display barcodes dynamically.

What is the BarcodeReader.Read method used for?

The BarcodeReader.Read method in IronBarcode is used to decode barcodes from images, making it a crucial part of implementing a barcode scanner in ASP.NET Core.

Is it possible to scan both QR Codes and barcodes using the same library in ASP.NET Core?

Yes, IronBarcode allows you to scan both QR Codes and various other barcode formats within the same ASP.NET Core application, providing a unified solution.

What are the benefits of using IronBarcode for barcode scanning in C#?

IronBarcode offers easy integration, support for multiple barcode formats, and robust server-side barcode generation capabilities, making it an efficient choice for barcode scanning in C# applications.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More
Ready to Get Started?
Nuget Downloads 2,094,439 | Version: 2026.3 just released
Still Scrolling Icon

Still Scrolling?

Want proof fast? PM > Install-Package BarCode
run a sample watch your string become a barcode.