Create an ASP.NET Core web app with barcode reader on web page using C#
1. Create new ASP.NET Core web app
Start Visual Studio 2022 and select "Create a new project".
Select "ASP.NET Core Web App" in the dialog, and then press "Next" button.
Create a new web project with name "OnBarcode.BarcodeReader.ASPNETCore.Demo".
Select .NET 6.0 (Long-term support), and then press "Create"
Now, all auto-generated files for ASP.NET Core barcode reader demo project could be found in the solution explorer.
Open the file "Program.cs" and make sure that it has enabled following Middlewares.
Select "ASP.NET Core Web App" in the dialog, and then press "Next" button.
Create a new web project with name "OnBarcode.BarcodeReader.ASPNETCore.Demo".
Select .NET 6.0 (Long-term support), and then press "Create"
Now, all auto-generated files for ASP.NET Core barcode reader demo project could be found in the solution explorer.
Open the file "Program.cs" and make sure that it has enabled following Middlewares.
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapRazorPages(); app.Run();
2. Install SkiaSharp and OnBarcode Barcode Reader for ASP.NET Core dll
Right-click "Dependencies" in the Solution Explorer, and select "Manage NuGet Packages".
Select "Browse" and use the search control to find "SkiaSharp" from the package source "nugget.org".
Choose the latest stable version to install SkiaSharp.
Check "Packages" in the Solution Explorer to ensure the installation is success.
Add OnBarcode Barcode Reader library for ASP.NET Core DLL reference "OnBarcode.Barcode.BarcodeScanner.Skia.dll".
Select "Browse" and use the search control to find "SkiaSharp" from the package source "nugget.org".
Choose the latest stable version to install SkiaSharp.
Check "Packages" in the Solution Explorer to ensure the installation is success.
Add OnBarcode Barcode Reader library for ASP.NET Core DLL reference "OnBarcode.Barcode.BarcodeScanner.Skia.dll".
3. Add C# code to scan, read barcodes in ASP.NET Core web page
Copy all following codes to replace the content of the file "Index.cshtml".
@page @model IndexModel @{ ViewData["Title"] = "Scan Barcode"; } <div class="text-center"> <form enctype="multipart/form-data" method="post"> <input asp-for="@Model.FormFile" type="file" style="width:300px; " onchange="document.getElementById('Submit').removeAttribute('disabled')" /> Barcode Type: <select name="BarcodeType"> @for (var i = 0; i < Model.BarcodeTypes.Length; i++) { @if (i == @Model.SelectedType) { <option value="@i" selected>@Model.BarcodeTypes[i]</option> } else { <option value="@i">@Model.BarcodeTypes[i]</option> } } </select> <br /><br /> <input id="Submit" type="submit" value="Scan Image" disabled /> </form> <br /> <table name="ScanResult" class="table-bordered" style="width:40%;" align="center"> <thead> <tr> <td colspan="2">Scan Result</td> </tr> </thead> <tbody> @if (Model.ResultCount >= 0) { <tr> <td colspan="2" align="left"> Number of valid barcodes: @Model.ResultCount </td> </tr> } @for (var i = 0; i < Model.ResultCount; i++) { var idx = i + 1; var msg = Model.Results[i]; <tr> <td style="width:10%;">@idx:</td> <td align="left">'@msg'</td> </tr> } </tbody> </table> </div>
Copy all following codes to replace the content in the file "Index.cshtml.cs".
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using OnBarcode.Barcode.BarcodeScanner; namespace OnBarcode.BarcodeReader.ASPNETCore.Demo.Pages { public class IndexModel : PageModel { public int SelectedType { get; set; } = 5; public String[] BarcodeTypes { get; set; } = new String[] { "AustraliaPost", "Codabar", "Code39", "Code39Extension", "Code93", "Code128", "DataMatrix", "EAN8", "EAN13", "Identcode", "IntelligentMail", "Interleaved2of5", "ISBN", "ISSN", "ITF14", "Leitcode", "PatchCode", "PDF417", "Planet", "Postnet", "QRCode", "RM4SCC", "UPCA", "UPCE" }; public IFormFile? FormFile { get; set; } public int ResultCount { get; set; } = -1; public String[] Results { get; set; } = new String[0]; public void OnGet() { } public Task<IActionResult> OnPost() { this.SelectedType = Int32.Parse(this.Request.Form["BarcodeType"]); if (this.FormFile != null) { var file = this.Request.Form.Files[0]; using (MemoryStream ms = new MemoryStream()) { file.CopyTo(ms); String[] result = BarcodeScanner.Scan(ms, (BarcodeType)this.SelectedType); if (result != null) { this.ResultCount = result.Length; this.Results = result; } else this.ResultCount = 0; } } return Task.FromResult<IActionResult>(Page()); } } }
4. Run barcode reader for ASP.NET Core web app
It is done. Now press "Ctrl+F5" to run the web project.
It launches the Kestrel server and opens the default browser. Use "Choose File" button to browse and add an image file with barcode(s).
Then, press "Scan Image" button to submit the form to server.
And all barcodes found in the image would be shown in a table as below.
Customize Barcode Scanner Options in C# ASP.NET web app
C# Barcode Reader library includes multiple barcode scanning options to allow ASP.NET web developers to reduce barcode reading time, improve barcode scanning accuracy in
C# ASP.NET, MVC, web application.
- Support one or multiple barcode types scanning at one time
- Quick to scan and detect a single barcode or find all barcodes with multiple barcode from an image file
- Scan defined image regions to read barcodes
- Multithreading barcode reading
Scan barcodes with multiple barcode formats
C# Barcode Reader library supports scan and read all barcodes with more than one barcode type inside an images.
The C# sample code below explains how to read all QR Code and Code 128 barcode text from an image.
The C# sample code below explains how to read all QR Code and Code 128 barcode text from an image.
ScanOptions opts = new ScanOptions(new List<BarcodeType> { BarcodeType.QRCode, BarcodeType.Code128 }); BarcodeDetail[] datas = BarcodeScanner.Scan("sample-barcodes.png", opts);
Scan one single barcode only or multiple barcodes
To improve the reading speed, barcode library provides one feature to scan maximum one barcode from an image. If the barcode reader library find a barcode on the image, it will
return the scanned barcode without executing scanning the remaining image area. This feature helps the scanning speed, if the image document contains one barcode only.
With the ScanSingle to true, if the barcode reader library has detected an barcode, it will stop scanning the rest area of image.
With the ScanSingle to true, if the barcode reader library has detected an barcode, it will stop scanning the rest area of image.
ScanOptions opts = new ScanOptions(BarcodeType.QRCode); opts.ScanSingle = true; BarcodeDetail[] datas = BarcodeScanner.Scan("sample-barcodes.png", opts);
Scanning barcode from defined image regions
For a high resolution image with large width and height (100 inch x 200 inch, and 3000 dpi), the barcode library will take huge memory and cpu resources to read, scan image data pixel by pixel.
To improve the barcode reading speed and accuracy performance, the barcode scanner support scanning barcodes from defined rectangle regions inside the image.
The following C# example source code shows how to scan Data Matrix barcodes from top 15% of the whole image. To view more details, click here: How to scan, read barcodes from defined image regions using C#?
To improve the barcode reading speed and accuracy performance, the barcode scanner support scanning barcodes from defined rectangle regions inside the image.
The following C# example source code shows how to scan Data Matrix barcodes from top 15% of the whole image. To view more details, click here: How to scan, read barcodes from defined image regions using C#?
ScanOptions opts = new ScanOptions(BarcodeType.DataMatrix); opts.SetScanRegions(new List<SRegion> {new SRegion(0, 0, 100, 15)}); BarcodeDetail[] datas = BarcodeScanner.Scan("data-matrix-barcodes.png", opts);
Multithreading barcode reading in C#
All modern computers and servers are multi-core CPUs. Apply multi-thread barcode scanning in C#, the barcode reader will improve the barcode reading speed significantly.
The following C# example source code demonstrates how to use 5 threads to scan and read PDF-417 barcodes simultaneously from an image file. To view more details, click here: How to read barcodes using C# multithreading in ASP.NET, Windows application?
The following C# example source code demonstrates how to use 5 threads to scan and read PDF-417 barcodes simultaneously from an image file. To view more details, click here: How to read barcodes using C# multithreading in ASP.NET, Windows application?
ScanOptions options = new ScanOptions(BarcodeType.PDF417); options.SetMaxMultiThreadCount(5); BarcodeDetail[] result = BarcodeScanner.Scan( new String[] { "SourceImage01.png", "SourceImage02.png", "SourceImage03.png" }, options);
How to read, parse barcode text message in C#?
Barcode symbology may use to encode numbers, plain text (ASCII text), and Unicode text content. C# Barcode Reader library includes utility features to handle these text formats.
Read barcode with ASCII text encoded
ASCII text (also known as plain text), includes 128 characters. 33 of them are non-printing characters (control characters), and 95 printable characters.
Code 128, Code 39 and most of the 2d barcodes supports encoding full ASCII characters. The following C# code show to how to scan and read ASCII characters in C# ASP.NET Core, MVC web application.
All non-printable characters in the barcode text will be expressed using ASCII char labels defined in ASCII table.
Code 128, Code 39 and most of the 2d barcodes supports encoding full ASCII characters. The following C# code show to how to scan and read ASCII characters in C# ASP.NET Core, MVC web application.
All non-printable characters in the barcode text will be expressed using ASCII char labels defined in ASCII table.
ScanOptions opts = new ScanOptions(BarcodeType.Code128); BarcodeDetail[] datas = BarcodeScanner.Scan("Code-128-sample.png", opts); foreach (BarcodeDetail obj in datas) { Console.WriteLine(" Barcode Text: " + obj.GetASCIITextMessage()); }
Read barcode with Unicode text encoded
OnBarcode Barcode library supports reading Unicode text from QR Code, Data Matrix and PDF-417 2d barcodes. Most of the Unicode text stored in 2d barcode are in binary data format.
To decode them, you also need convert byte array data into Unicode text by using the same text encoding mode. Most of the common encoding mode is UTF8.
BarcodeDetail[] datas = BarcodeScanner.ScanInDetails("sample-qrcode.png", BarcodeType.QRCode); for (int j = 0; j < datas.Length; j++) { byte[] dataInBytes = datas[j].GetDataBytes(); string textMsgDecoded = System.Text.Encoding.UTF8.GetString(dataInBytes); Console.WriteLine("message: " + textMsgDecoded); }
Summary
OnBarcode Barcode software is a mature .NET application library for reading multiple barcode image formats.
Using C# Barcode Reader Library, ASP.NET professionals are easy to enable barcode online scanning and reading functions into ASP.NET Core, MVC web app.
The barcode library also supports barcode reading in Windows app.
