ASP.NET Core 條碼掃描器

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

簡介

ASP.NET Core 是一個跨平台框架,用於構建現代網頁應用程序。 其 Razor Pages 模型提供了一種基於頁面的 HTTP 請求處理方法,這使得它非常適合於伺服器端條碼處理。 使用 IronBarcode,上傳的影像可以作為 IFormFile 物件接收,轉換為位元組數組,並直接傳遞給條碼讀取器,而無需將臨時文件寫入磁碟。

本文講解了如何將 IronBarcode 整合到一個 ASP.NET Core Razor Pages 應用程序中,以便從上傳的影像中掃描條碼和 QR 碼,以及從伺服器生成條碼。

IronBarcode:C# 條碼程式庫

IronBarcode 提供了一個強大的 API,用於在 .NET 應用程序中讀取和寫入條碼。 該程式庫在內部處理影像處理,因此開發人員可以將原始位元組、文件路徑或流直接傳遞給 BarcodeReader.Read 方法,而無需另啟影像處理程式庫。 它支持多種條碼格式,包括 QR CodeCode 128Code 39PDF417EAN 及其他許多格式。

對於網頁應用程序來說,IronBarcode 特別有用,因為它完全在記憶體中處理影像。 上傳的文件不需要保存到磁碟,簡化了部署並減少了清理工作負擔。 同一個程式庫也能使用 BarcodeWriter.CreateBarcode 生成條碼,使之能夠同時擔負讀取和寫入的功能。

在 ASP.NET Core 中構建條碼掃描器的步驟

按照這些步驟創建一個基於網頁的條碼掃描器,使用 ASP.NET Core Razor Pages 和 IronBarcode。

必要條件

  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 Package Manager Console 安裝 IronBarcode 程式庫。 導航到 Tools > NuGet Package Manager > Package Manager Console 在 Visual Studio 中並運行:

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

布局使用了已經包含在預設 ASP.NET Core 模板中的 Bootstrap 類。 表單提交到 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 並轉換為位元組數組。 這與 網頁掃描器範例 中使用的方法相同,但適應了 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 畫布)的應用程序,同樣的 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

伺服器端使用 BarcodeWriter.CreateBarcode 生成的 QR 代碼

有關更多條碼生成選項,請參見 條碼影像生成教程條碼樣式指南

運行應用程序

從 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 內部處理影像處理,因此無論使用哪種網頁框架,整合所需的代碼都非常少。

有關其他 .NET 平台上的條碼讀取指南,請參見 .NET MAUI 條碼掃描器教程條碼讀取指南。 在 IronBarcode 上獲取更多教程,參見 條碼讀取教程

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

IronBarcode 必須獲得許可才能進行開發和商業用途。 許可詳情可在 此處找到。

常見問題解答

如何在ASP.NET Core中使用Razor Pages實現條碼掃描器?

您可以在ASP.NET Core Razor Pages專案中使用IronBarcode來實現條碼掃描器。該程式庫允許您通過上傳圖片並用BarcodeReader.Read處理它們來讀取各種條碼格式,如QR Codes、Code 128和Code 39。

使用IronBarcode可以讀取哪些類型的條碼?

IronBarcode支持讀取多種條碼格式,包括QR Codes、Code 128和Code 39,使其能為多種應用程序所用。

如何在ASP.NET Core專案中上傳圖片進行條碼掃描?

在ASP.NET Core專案中,您可以使用IFormFile來上傳圖片。IronBarcode會處理這些圖片以讀取其中的條碼。

IronBarcode可以在ASP.NET Core上生成伺服器端的條碼嗎?

可以,IronBarcode可以在ASP.NET Core上使用BarcodeWriter.CreateBarcode方法生成伺服器端的條碼,允許您動態創建和顯示條碼。

BarcodeReader.Read方法用於什麼?

IronBarcode中的BarcodeReader.Read方法用於解碼圖片中的條碼,這是實現ASP.NET Core中條碼掃描器的重要組成部分。

在ASP.NET Core中可以使用同一個程式庫掃描QR Codes和條碼嗎?

可以,IronBarcode允許您在同一個ASP.NET Core應用程式中掃描QR Codes及其他各種條碼格式,提供一個統一的解決方案。

使用IronBarcode來進行C#中的條碼掃描有什麼好處?

IronBarcode提供了容易的整合,多種條碼格式支持,以及強大的伺服器端條碼生成功能,使其成為C#應用程式中條碼掃描的高效選擇。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 2,108,094 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。