ASP.NET Core 條碼掃描器
介紹
ASP.NET Core是一個構建現代Web應用程式的跨平台框架。 其Razor Pages模型提供了基於頁面的HTTP請求處理方式,非常適合於伺服器端條碼處理。 透過 IronBarcode,上傳的圖像可被接收為 IFormFile 物件,轉換為位元組陣列,並直接傳遞給 BARCODE 讀取器,無需將臨時檔案寫入磁碟。
本文逐步演示將IronBarcode整合到ASP.NET Core Razor Pages應用程式中,以從上傳的圖像中掃描條碼和QR碼,並從伺服器生成條碼。
如何在ASP.NET Core中讀取及掃描條碼
- 安裝C#程式庫以讀取和掃描條碼
- 創建一個新的ASP.NET Core Razor Pages專案
- 設計文件上傳表單以接受條碼圖像
- 使用
Read方法來掃描上傳的圖像以查找條碼 - 在頁面上顯示解碼的條碼值
IronBarcode: C# 條碼程序庫
IronBarcode為在.NET應用程式中讀寫條碼提供了一個強大的API。 該函式庫在內部處理影像處理,因此開發人員可直接將原始位元組、檔案路徑或資料流傳遞給 BarcodeReader.Read 方法,無需額外使用影像處理函式庫。 它支援廣泛的條碼格式,包括QR Code、Code 128、Code 39、PDF417、_EAN_等許多其他格式。
對於Web應用程式來說,IronBarcode特別有用,因為它在記憶體中完全處理圖像。 上傳的文件不需要保存到磁碟,從而簡化了部署並減少了清理開銷。 該函式庫亦能透過 BarcodeWriter.CreateBarcode 生成 BARCODE,使其成為讀寫功能的一站式依賴項。
在ASP.NET Core中建立條碼掃描器的步驟
遵循以下步驟,使用ASP.NET Core Razor Pages和IronBarcode創建基於Web的條碼掃描器。
先決條件
- Visual Studio 2022或更新版本(或任何支援.NET的IDE)
- .NET 6.0或更新版本的SDK
創建專案
創建一個新的ASP.NET Core Web App(Razor Pages)專案。 這可以通過Visual Studio的專案嚮導完成,或者從命令行完成:
dotnet new webapp -n BarcodeWebApp
dotnet new webapp -n BarcodeWebApp
安裝 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>
佈局使用已包含在預設ASP.NET Core模板中的Bootstrap類。 表單提交至 Upload 頁面處理程序,條件式區塊會顯示上傳圖片的預覽、解碼結果或錯誤訊息。
樣本輸入條碼
以下樣本條碼可用於測試掃描器。 每個圖像編碼不同的格式和值:
QR碼編碼"https://ironsoftware.com"
Code 128條碼編碼"IronBarcode-2026"
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.Co/pyToAsync(ms);
byte[] imageBytes = ms.ToArray();
// Store image as base64 for preview display
string base64 = Convert.ToBase64String(imageBytes);
ImageDataUrl = $"data:{UploadedFile.Co/ntentType};base64,{base64}";
// Read barcode from uploaded image bytes
var results = BarcodeReader.Read(imageBytes);
if (results != null && results.Co/unt() > 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.Co/pyToAsync(ms);
byte[] imageBytes = ms.ToArray();
// Store image as base64 for preview display
string base64 = Convert.ToBase64String(imageBytes);
ImageDataUrl = $"data:{UploadedFile.Co/ntentType};base64,{base64}";
// Read barcode from uploaded image bytes
var results = BarcodeReader.Read(imageBytes);
if (results != null && results.Co/unt() > 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
上方程式碼的關鍵步驟:
- 接收上傳資料 -
IFormFile透過[BindProperty]進行綁定,並在 POST 處理程序中接收。 - 轉換為位元組 - 檔案被複製到
MemoryStream並轉換為位元組陣列。 此方法與網頁掃描器範例相同,僅將 base64 字串替換為 .NET Core 的IFormFile格式。 - 讀取 BARCODE -
BarcodeReader.Read(imageBytes)會處理影像並回傳所有偵測到的 BARCODE。 - 顯示結果 - 所有檢測到的條碼值被連續拼接並顯示在UI中。
以下GIF展示了條碼讀取器的運行,在ASP.NET Core應用程式上傳條碼圖像並顯示解碼結果:
條碼讀取器在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})";
}
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
此方法透過以逗號為分隔符號,並提取實際的 Base64 有效載荷,同時處理原始 Base64 格式與資料 URI 格式(例如 data:image/png;base64,...)。 如需此模式的完整Blazor實作,請參閱Blazor整合指南。
在伺服器上生成條碼
IronBarcode 亦可於伺服器端產生 BARCODE。透過 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
生成的條碼將作為檔案下載返回。 下圖顯示由 OnPostGenerate 處理器產生的 QR 碼輸出:
使用BarcodeWriter.CreateBarcode在伺服器端生成的QR碼
運行應用程式
從Visual Studio或命令列運行專案:
dotnet run
dotnet run
應用程式將在 launchSettings.json 中指定的埠號上啟動(通常為 https://localhost:5001 或類似埠號)。 導航到首頁以查看條碼掃描器介面。
結論
本文展示了如何使用ASP.NET Core Razor Pages和IronBarcode構建伺服器端條碼掃描器。 相同的方法適用於ASP.NET Core MVC控制器、Web API端點和Blazor Server應用程式,只需調整影像資料的接收方式。 IronBarcode在內部處理影像處理,因此不論網頁架構如何,整合所需的代碼都很少。
如需在其他.NET平台上讀取條碼,請參閱<net MAUI條碼掃描器教程與條碼讀取如何指南。 在IronBarcode上獲取更多教程,請參閱讀取條碼教程。
若要快速上手,請下載完整的 BarcodeWebApp 專案,並使用 dotnet run 執行它。
IronBarcode 必須獲得許可才能用於開發和商業用途。 授權細節可在此處找到。
常見問題
如何在ASP.NET Core中使用Razor Pages實現條碼掃描器?
您可以在ASP.NET Core的Razor Pages專案中使用IronBarcode來實現條碼掃描器。該程式庫允許您通過上傳圖像並使用BarcodeReader.Read方法處理它們來讀取多種條碼格式,如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碼和其他多種條碼格式,提供了統一的解決方案。
在C#中使用IronBarcode進行條碼掃描有哪些好處?
IronBarcode提供了簡便的整合,支持多種條碼格式,並且具有強大的伺服器端條碼生成功能,這使其成為C#應用程式中條碼掃描的高效選擇。
IronBarcode可以處理1D和2D條碼嗎?
IronBarcode能夠處理1D和2D條碼,支援從簡單產品標籤到複雜數據編碼的廣泛應用。
IronBarcode的商業用途有授權選項嗎?
Iron Software為IronBarcode提供各種授權選項,包括針對企業級應用的商業授權,確保符合業務需求。
IronBarcode支援批次處理條碼嗎?
是的,IronBarcode支援批次處理,允許開發者在一次操作中生成或讀取多個條碼,提升大規模應用的效率。

