ASP.NET Core 条码扫描器

This article was translated from English: Does it need improvement?
Translated
View the article in English

简介

ASP.NET Core 是一个用于构建现代 Web 应用程序的跨平台框架。 其 Razor Pages 模型提供了一种页面为基础的处理 HTTP 请求的方法,非常适合服务器端条码处理。 使用 IronBarcode,上传的图像可以作为 IFormFile 对象接收,转换为字节数组,直接传递给条码阅读器,而无需将临时文件写入磁盘。

本文演示了如何将 IronBarcode 集成到 ASP.NET Core Razor Pages 应用程序中,以扫描上传图像中的条码和 QR 码,并从服务器生成条码。

IronBarcode:C# 条形码库

IronBarcode 为 .NET 应用程序提供了一个强大的读写条码的 API。 该库内部处理图像处理,因此开发者可以将原始字节、文件路径或流直接传递给 BarcodeReader.Read 方法,而无需单独的图像处理库。 它支持广泛的条码格式,包括 QR CodeCode 128Code 39PDF417EAN 等。

对于 Web 应用程序,IronBarcode 特别有用,因为它完全在内存中处理图像。 上传的文件不需要保存到磁盘,这简化了部署并减少了清理的工作量。 同一个库也可以通过 BarcodeWriter.CreateBarcode 生成条码,使其成为读取和写入的单一依赖。

在 ASP.NET Core 中构建条码扫描器的步骤

按照以下步骤使用 ASP.NET Core Razor Pages 和 IronBarcode 创建一个基于 Web 的条码扫描器。

前提条件

  1. Visual Studio 2022 或更高版本(或任何支持 .NET 的 IDE)
  2. .NET 6.0 或更高版本的 SDK

创建项目

创建一个新的 ASP.NET Core Web App (Razor Pages) 项目。 这可以通过 Visual Studio 的项目向导或命令行完成:

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

安装 IronBarcode 库

通过 NuGet 包管理器控制台安装 IronBarcode 库。 在 Visual Studio 中导航到 Tools > NuGet Package Manager > Package Manager Console 并运行:

Install-Package BarCode

或者,可以通过命令行使用 dotnet add package BarCode 安装它。 最新版本可在 NuGet 网站 上获取。

前端

前端由文件上传表单和结果显示区域组成。 表单使用 enctype="multipart/form-data" 来处理二进制文件上传。 当检测到条码时,结果将显示在上传图像下方的成功提示中。

用以下内容替换 Index.cshtml 文件中的内容:

@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

布局使用 Bootstrap 类,这些类已包含在默认的 ASP.NET Core 模板中。 表单提交到 Upload 页面处理程序,条件块显示上传的图像预览、解码结果或错误消息。

示例输入条码

以下示例条码可用于测试扫描器。 每个图像编码不同的格式和值:

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

QR Code 编码 "https://ironsoftware.com"

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

Code 128 条码编码 "IRONBARCODE-2026"

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

Code 39 条码编码 "HELLO123"

使用 IronBarcode 进行条码扫描

服务器端逻辑在 OnPostUploadAsync 方法中处理上传的文件。 上传的 IFormFile 被读取为字节数组,并直接传递给 BarcodeReader.Read。 这避免了保存临时文件,并将处理完全保留在内存中。

用以下内容替换 Index.cshtml.cs 中的内容:

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

上述代码中的关键步骤:

  1. 接收上传 - IFormFile 通过 [BindProperty] 绑定,并在POST处理程序中接收。
  2. 转换为字节 - 文件被复制到 MemoryStream 并转换为字节数组。 这与 web 扫描器示例 中使用的方法相同,但经过调整以适应 ASP.NET Core 的 IFormFile 而不是 base64 字符串。
  3. 读取条码 - BarcodeReader.Read(imageBytes) 处理图像并返回检测到的所有条码。
  4. 显示结果 - 所有检测到的条码值被连接并显示在 UI 中。

以下 GIF 演示了条码阅读器的实际操作,上传条码图像并显示解码结果:

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

在 ASP.NET Core 应用程序中扫描上传图像的条码阅读器

处理 Base64 图像数据

对于以 base64 字符串形式接收图像数据的应用程序(例如来自网络摄像头捕获或 JavaScript canvas),同样的 BarcodeReader.Read 方法可以处理从 base64 解码的字节数组。这种模式在通过 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})";
}
$vbLabelText   $csharpLabel

这种方法同时处理原始 base64 和数据 URI 格式(例如,data:image/png;base64,...)通过逗号拆分并获取实际的 base64 负载。 有关使用此模式的完整 Blazor 实现,请参见 Blazor 集成指南

在服务器上生成条码

IronBarcode 也可以在服务器端生成条码。通过 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");
}
$vbLabelText   $csharpLabel

生成的条码以文件下载的形式返回。 以下图像显示了 OnPostGenerate 处理器生成的 QR 码输出:

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

服务器端生成 QR 码使用 BarcodeWriter.CreateBarcode

有关更多条码生成选项,请参见 条码图像生成教程条码样式指导

运行应用程序

通过 Visual Studio 或命令行运行项目:

dotnet run
dotnet run
SHELL

应用程序启动在 launchSettings.json 指定的端口(通常是 https://localhost:5001 或类似端口)。 导航到主页以查看条码扫描器界面。

结论

本文展示了如何使用 ASP.NET Core Razor Pages 和 IronBarcode 构建服务器端条码扫描器。 通过调整接收图像数据的方式,同样的方法适用于 ASP.NET Core MVC 控制器、Web API 端点和 Blazor Server 应用程序。 IronBarcode 内部处理图像处理,因此无论使用哪种 Web 框架,集成都需要极少的代码。

有关在其他 .NET 平台中读取条码,请参见 .NET MAUI 条码扫描器教程条码读取指导。 获取更多有关 IronBarcode 的教程从 读取条码教程

要快速入门,请下载完整的BarcodeWebApp项目,然后使用 dotnet run 运行。

IronBarcode 必须获得开发和商业使用的许可。 许可详情可在 这里 获取。

常见问题解答

如何在ASP.NET Core中使用Razor Pages实现条码扫描仪?

您可以在您的ASP.NET Core Razor Pages项目中使用IronBarcode实现条码扫描仪。该库允许您读取各种条码格式,如QR码、Code 128和Code 39,通过上传图像并用BarcodeReader.Read处理。

IronBarcode可以读取哪些类型的条码?

IronBarcode支持读取多种条码格式,包括QR码、Code 128和Code 39,使其适用于各种应用程序。

如何在ASP.NET Core项目中上传图像以进行条码扫描?

在ASP.NET Core项目中,您可以使用IFormFile上传图像。IronBarcode处理这些图像以读取其中包含的条码。

IronBarcode能否在ASP.NET Core中服务器端生成条码?

是的,IronBarcode可以使用BarcodeWriter.CreateBarcode方法在ASP.NET Core中服务器端生成条码,使您能够动态创建和显示条码。

BarcodeReader.Read方法用于什么?

IronBarcode中的BarcodeReader.Read方法用于从图像中解码条码,是在ASP.NET Core中实现条码扫描仪的重要部分。

是否可以在ASP.NET Core中使用同一个库扫描QR码和条码?

是的,IronBarcode允许您在同一ASP.NET Core应用程序中扫描QR码和其他多种条码格式,提供统一的解决方案。

使用IronBarcode进行C#条码扫描有什么好处?

IronBarcode提供了简单的集成、支持多种条码格式以及强大的服务器端条码生成能力,使其成为C#应用程序中进行条码扫描的有效选择。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 2,121,847 | 版本: 2026.3 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package BarCode
运行示例 观看您的字符串变成 BarCode。