IronBarcode 開始使用 ASP.NET Core條碼掃描器 ASP.NET Core Barcode Scanner Curtis Chau 更新:2026年3月1日 下載 IronBarcode NuGet 下載 DLL 下載 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 This article was translated from English: Does it need improvement? Translated View the article in English 介紹 ASP.NET Core is a cross-platform framework for building modern web applications. Its Razor Pages model offers a page-based approach to handling HTTP requests, which makes it well suited for server-side barcode processing. With IronBarcode, uploaded images can be received as IFormFile objects, converted to byte arrays, and passed directly to the barcode reader without writing temporary files to disk. This article walks through integrating IronBarcode into an ASP.NET Core Razor Pages application to scan barcodes and QR codes from uploaded images, as well as generate barcodes from the server. How to Read & Scan Barcodes in ASP.NET Core Install the C# library to read and scan barcodes Create a new ASP.NET Core Razor Pages project Design the file upload form to accept barcode images Use the `Read` method to scan the uploaded image for barcodes Display the decoded barcode value on the page IronBarcode:C# 條碼庫 IronBarcode provides a robust API for reading and writing barcodes in .NET applications. The library handles image processing internally, so developers can pass raw bytes, file paths, or streams directly to the BarcodeReader.Read method without needing separate image processing libraries. It supports a wide range of barcode formats including QR Code, Code 128, Code 39, PDF417, EAN, and many others. For web applications, IronBarcode is particularly useful because it processes images entirely in memory. Uploaded files never need to be saved to disk, which simplifies deployment and reduces cleanup overhead. The same library also generates barcodes with BarcodeWriter.CreateBarcode, making it a single dependency for both reading and writing. Steps to Build a Barcode Scanner in ASP.NET Core Follow these steps to create a web-based barcode scanner using ASP.NET Core Razor Pages and IronBarcode. 先決條件 Visual Studio 2022 or later (or any IDE with .NET support) .NET 6.0 or later SDK Create the Project Create a new ASP.NET Core Web App (Razor Pages) project. This can be done through Visual Studio's project wizard or from the command line: dotnet new webapp -n BarcodeWebApp dotnet new webapp -n BarcodeWebApp SHELL 安裝 IronBarcode 庫 Install the IronBarcode library using the NuGet Package Manager Console. Navigate to Tools > NuGet Package Manager > Package Manager Console in Visual Studio and run: Install-Package BarCode Alternatively, install it from the command line with dotnet add package BarCode. The latest version is available on the NuGet website. Frontend The frontend consists of a file upload form and a result display area. The form uses enctype="multipart/form-data" to handle binary file uploads. When a barcode is detected, the result appears in a success alert below the uploaded image. Replace the content in the Index.cshtml file with the following: @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 The layout uses Bootstrap classes already included in the default ASP.NET Core template. The form submits to the Upload page handler, and conditional blocks display the uploaded image preview, the decoded result, or an error message. Sample Input Barcodes The following sample barcodes can be used to test the scanner. Each image encodes a different format and value: QR Code encoding "https://ironsoftware.com" Code 128 barcode encoding "IRONBARCODE-2026" Code 39 barcode encoding "HELLO123" Barcode Scanning with IronBarcode The server-side logic handles the uploaded file in the OnPostUploadAsync method. The uploaded IFormFile is read into a byte array, which is passed directly to BarcodeReader.Read. This avoids saving temporary files and keeps the processing entirely in memory. Replace the content in Index.cshtml.cs with: 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 The key steps in the code above: Receive the upload - The IFormFile is bound via [BindProperty] and received in the POST handler. Convert to bytes - The file is copied to a MemoryStream and converted to a byte array. This is the same approach used in the web scanner example, adapted for ASP.NET Core's IFormFile instead of base64 strings. Read the barcode - BarcodeReader.Read(imageBytes) processes the image and returns all detected barcodes. Display the result - All detected barcode values are joined and displayed in the UI. The following GIF demonstrates the barcode reader in action, uploading a barcode image and displaying the decoded result: Barcode reader scanning an uploaded image in the ASP.NET Core application Processing Base64 Image Data For applications that receive image data as base64 strings (e.g., from webcam captures or JavaScript canvas), the same BarcodeReader.Read method works with byte arrays decoded from base64. This pattern is common in single-page applications that send image data via 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 This approach handles both raw base64 and data URI formats (e.g., data:image/png;base64,...) by splitting on the comma and taking the actual base64 payload. For a complete Blazor implementation using this pattern, see the Blazor integration guide. Generating Barcodes on the Server IronBarcode can also generate barcodes server-side. Adding a generation endpoint to the same application is straightforward with 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 The generated barcode is returned as a file download. The following image shows the QR code output produced by the OnPostGenerate handler: QR code generated server-side with BarcodeWriter.CreateBarcode For more barcode generation options, see the barcode image generation tutorial and the barcode styling guide. 運行應用程式 Run the project from Visual Studio or the command line: dotnet run dotnet run SHELL The application starts on the port specified in launchSettings.json (typically https://localhost:5001 or similar). Navigate to the home page to see the barcode scanner interface. 結論 This article demonstrated how to build a server-side barcode scanner using ASP.NET Core Razor Pages and IronBarcode. The same approach works with ASP.NET Core MVC controllers, Web API endpoints, and Blazor Server applications by adapting how the image data is received. IronBarcode handles the image processing internally, so the integration requires minimal code regardless of the web framework. For reading barcodes in other .NET platforms, see the .NET MAUI barcode scanner tutorial and the barcode reading how-to guides. Get more tutorials on IronBarcode from the reading barcodes tutorial. To get started quickly, download the complete BarcodeWebApp project and run it with dotnet run. IronBarcode 必須獲得許可才能用於開發和商業用途。 Licensing details are available here. 常見問題解答 如何在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,121,847 | 版本: 2026.3 剛剛發布 開始免費試用 免費 NuGet 下載 總下載量:2,121,847 查看許可證 還在捲動嗎? 想要快速證明? PM > Install-Package BarCode 執行範例 看您的字串變成 BarCode。 免費 NuGet 下載 總下載量:2,121,847 查看許可證