ASP.NET Core 條碼掃描器
介紹
ASP.NET Core是一個跨平臺框架,用於建構現代網頁應用程式。 其Razor Pages模型提供了基於頁面的HTTP請求處理方式,非常適合於伺服器端條碼處理。 使用IronBarcode,上傳的圖像可以接收為IFormFile物件,轉換為位元組陣列,並直接傳遞給條碼閱讀器而不需將臨時文件寫入磁碟。
本文逐步演示將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生成條碼,這使得它成為讀寫雙方都依賴的單一依賴項。
在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
安裝 IronBarcode 庫
使用NuGet套件管理控制台安裝IronBarcode程式庫。 在Visual Studio中導航到Tools > NuGet Package Manager > Package Manager Console並執行:
或者,從命令行安裝它,使用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>
佈局使用已包含在預設ASP.NET Core模板中的Bootstrap類。 表單提交給Upload頁面處理程序,條件塊顯示上傳的圖像預覽、解碼結果或錯誤訊息。
樣本輸入條碼
以下樣本條碼可用於測試掃描器。 每個圖像編碼不同的格式和值:

QR Code編碼"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.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 ClassImports 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並轉換為位元組陣列。 這與網頁掃描器範例中使用的方法相同,適用於ASP.NET Core的IFormFile,而不是base64字串。 - 讀取條碼 -
BarcodeReader.Read(imageBytes)處理圖像並返回所有檢測到的條碼。 - 顯示結果 - 所有檢測到的條碼值被連續拼接並顯示在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 FunctionPublic 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格式和data URI格式(例如data:image/png;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 FunctionPublic 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
應用程式在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 必須獲得許可才能用於開發和商業用途。 授權詳細信息可在此處獲得。
常見問題
使用IronBarcode在ASP.NET Core Razor Pages應用程式中的主要目的是什麼?
IronBarcode用於從上傳的圖像中掃描條形碼和QR碼,並在ASP.NET Core Razor Pages應用程式中生成伺服器端條形碼。
IronBarcode如何在網頁應用程式中處理圖像?
IronBarcode完全在記憶體中處理圖像,這意味著無需將上傳的檔案存儲到磁碟,簡化了部署並減少了清理負擔。
IronBarcode可以在ASP.NET Core應用程式中讀取哪些類型的條形碼?
IronBarcode支持各種條形碼格式,包括QR碼、Code 128、Code 39、PDF417、EAN等。
在ASP.NET Core中使用IronBarcode設置條形碼掃描器涉及哪些步驟?
這些步驟包括安裝IronBarcode程式庫、創建ASP.NET Core Razor Pages專案、設計文件上傳表單、使用Read方法掃描條形碼,並將解碼後的條形碼值顯示在網頁上。
IronBarcode可以在ASP.NET Core應用程式中生成條形碼嗎?
是的,IronBarcode可以通過使用BarcodeWriter.CreateBarcode方法在伺服器端生成條形碼,例如生成QR碼。
使用IronBarcode的伺服器端條形碼處理有什麼好處?
主要的好處是所有圖像處理均在記憶體中進行,允許高效的掃描和生成,無需臨時文件,從而提高了性能並減少了資源使用。
如何在ASP.NET Core專案中安裝IronBarcode程式庫?
可以使用Visual Studio中的NuGet套件管理控制台或通過命令行使用命令:dotnet add package BarCode來安裝IronBarcode程式庫。
IronBarcode提供什麼方法來從字節數組中讀取條形碼?
IronBarcode提供BarcodeReader.Read方法來處理圖像並直接從字節數組中讀取條形碼。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。