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 程式庫

using 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

布局已使用預設的 ASP.NET Core 模板中包含的 Bootstrap 類。 表單提交到 Upload 頁面處理器,條件塊顯示上傳圖像預覽,解碼結果或錯誤資訊。

範例輸入條碼

以下範例條碼可用於測試掃描器。 每個影像編碼不同的格式和數值:

ASP.NET Core 條碼掃描器 - 編碼 URL 的範例 QR Code 輸入

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

上述程式碼中的關鍵步驟:

  1. 接收上傳 - IFormFile 綁定通過 [BindProperty] 並在 POST 處理器中接收。
  2. 轉換為字節 - 檔案被複製到 MemoryStream 並轉換為字節陣列。 這和在 網路掃描器例子中使用的方法相同,只是針對 ASP.NET Core 的 IFormFile 進行了調整,而不是 base64 字串。
  3. 讀取條碼 - BarcodeReader.Read(imageBytes) 處理影像並返回所有檢測到的條碼。
  4. 顯示結果 - 所有檢測到的條碼值合併並在 UI 中顯示。

以下 GIF 演示了條碼讀取器的工作原理,從上傳條碼圖像到顯示解碼結果:

ASP.NET Core 條碼掃描器 - 上傳並讀取條碼的示範

條碼讀取器在 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})";
}
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

這種方法處理原始 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");
}
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

生成的條碼以檔案下載形式返回。 下圖顯示了由 OnPostGenerate 處理器生成的 QR 碼輸出:

ASP.NET Core 條碼掃描器 - 伺服器產生的 QR code 輸出

伺服器端生成的 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 伺服器應用程式,通過調整圖像資料的接收方式。 IronBarcode 在內部處理影像處理,因此無論使用哪種網頁框架,整合所需的程式碼都很少。

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

要快速入門,下載完整的 BarcodeWebApp 專案 並使用 dotnet run 運行。

IronBarcode 必須獲得開發和商業用途的授權。 授權詳情可在這裡找到。

常見問題

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

您可以在ASP.NET Core Razor頁面專案中使用IronBarcode來實現條碼掃描器。這個程式庫允許您通過上傳和處理圖像來讀取各種條碼格式,如QR碼、Code 128和Code 39。

使用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#應用程式中進行條碼掃描的高效選擇。

IronBarcode可以處理1D和2D條碼嗎?

IronBarcode能夠處理1D和2D條碼,支援從簡單產品標籤到複雜資料編碼的廣泛應用。

IronBarcode的商業使用有限權選項有哪些?

Iron Software為IronBarcode提供多種授權選擇,包括針對企業級應用的商業授權,以確保符合企業需求。

IronBarcode支援條碼的批量處理嗎?

是的,IronBarcode支援批量處理,允許開發人員在一次操作中生成或讀取多個條碼,提高大規模應用的效率。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 2,317,217 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速驗證嗎? PM > Install-Package BarCode
運行範例觀看您的字串成為條碼。