Prerequisites
Download and install the following software on your computer
- Visual Studio 2022
- .NET 6.0 SDK
- OnBarcode.Barcode.BarcodeScanner.dll
Create a new ASP.NET Core MVC web app with barcode reader on web page using C#
1. Create new ASP.NET Core MVC web app
Start Visual Studio 2022 and select "Create a new project".
Select "ASP.NET Core Web App (Model-View-Controller)" in the dialog, and then press "Next" button.
Create a new project with name "OnBarcodeReaderASPNETCoreMVCDemo".
Choose ".NET 6.0 (Long-term support)"
Now, all auto-generated files for ASP.NET Core MVC barcode reader demo project could be found in the solution explorer.
Select "ASP.NET Core Web App (Model-View-Controller)" in the dialog, and then press "Next" button.
Create a new project with name "OnBarcodeReaderASPNETCoreMVCDemo".
Choose ".NET 6.0 (Long-term support)"
Now, all auto-generated files for ASP.NET Core MVC barcode reader demo project could be found in the solution explorer.
2. Install Barcode Reader Library dll and NuGet Package
Add OnBarcode Barcode Reader library for ASP.NET Core DLL reference "OnBarcode.Barcode.BarcodeScanner.dll".
Right-click "Dependencies" in the Solution Explorer, and select "Manage NuGet Packages".
Select "Browse" and use the search control to find "System.Drawing.Common" from the package source "nugget.org".
Choose the version 6.0.0 or later to install the package.
Check "Packages" in the Solution Explorer to ensure the installation is success.
Right-click "Dependencies" in the Solution Explorer, and select "Manage NuGet Packages".
Select "Browse" and use the search control to find "System.Drawing.Common" from the package source "nugget.org".
Choose the version 6.0.0 or later to install the package.
Check "Packages" in the Solution Explorer to ensure the installation is success.
3. Add C# data model classes to the ASP.NET Core MVC project
Right-click the Models folder in the Solution Explorer and choose Add > Class to open the Add New Item dialog.
Then add a class item with name "IndexViewModel.cs".
Add the following C# codes to class "IndexViewModel.cs".
Then add a class item with name "IndexViewModel.cs".
Add the following C# codes to class "IndexViewModel.cs".
namespace OnBarcodeReaderASPNETCoreMVCDemo.Models { public class IndexViewModel { public List<String> BarcodeTypes { get; set; } = new List<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 int SelectedTypeIndex { get; set; } public IFormFile? FormFile { get; set; } } }
Then add a new class item with name "ShowResultViewModel.cs".
Add the following C# codes to class "ShowResultViewModel.cs".
Add the following C# codes to class "ShowResultViewModel.cs".
namespace OnBarcodeReaderASPNETCoreMVCDemo.Models { public class ShowResultViewModel { public String[]? DataMessages { get; set; } } }
4. Add C# Views to the ASP.NET Core MVC project
View : Index
Select existed view "Index.cshtml" and replace ALL content by following codes.
Select existed view "Index.cshtml" and replace ALL content by following codes.
@model IndexViewModel; @{ ViewData["Title"] = "Home Page"; } <div class="text-center"> <br /> <form asp-action="ShowResult" method="post" enctype="multipart/form-data"> <input Name="FormFile" type="file" style="width:300px; " onchange="document.getElementById('Submit').removeAttribute('disabled')" /> Barcode Type: <select asp-for="SelectedTypeIndex" asp-items="Model.BarcodeTypes.Select((item, index) => new SelectListItem { Text = item, Value = index.ToString(), Selected = index == Model.SelectedTypeIndex })"> </select> <br /><br /> <input id="Submit" type="submit" value="Scan Image" disabled /> </form> </div>
View : ShowResult
Right click the folder Views/Home, and choose Add > View.
Select "Razor View - Empty" to open "Add New Item" dialog.
Add a new view "ShowResult.cshtml" to the project with following layout.
Right click the folder Views/Home, and choose Add > View.
Select "Razor View - Empty" to open "Add New Item" dialog.
Add a new view "ShowResult.cshtml" to the project with following layout.
@model ShowResultViewModel; @{ ViewData["Title"] = "Show Result"; } <div style="display:flex;justify-content:center"> <table name="ScanResult" class="table-bordered" style="width:40%;" align="center"> <thead> <tr> <td colspan="2">Scan Result</td> </tr> </thead> <tbody> @if (Model.DataMessages != null && Model.DataMessages.Length >= 0) { <tr> <td colspan="2" align="left"> Number of valid barcodes: @Model.DataMessages.Length </td> </tr> @for (var i = 0; i < Model.DataMessages.Length; i++) { var idx = i + 1; var msg = Model.DataMessages[i]; <tr> <td style="width:10%;">@idx:</td> <td align="left">'@msg'</td> </tr> } } </tbody> </table> </div> <br /><br /><br /> <a asp-action="Index">Back to Index</a>
5. Update controller class C# source code
Adding two methods Index and ShowResult to class "HomeController.cs".
Replace the contents of controller class "HomeController.cs" with following code.
Replace the contents of controller class "HomeController.cs" with following code.
using Microsoft.AspNetCore.Mvc; using OnBarcodeReaderASPNETCoreMVCDemo.Models; using System.Diagnostics; using OnBarcode.Barcode.BarcodeScanner; namespace OnBarcodeReaderASPNETCoreMVCDemo.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { IndexViewModel model = new IndexViewModel(); // Set default barcode type to Code 128 model.SelectedTypeIndex = 5; return View(model); } [HttpPost] public async Task<IActionResult> ShowResult(IndexViewModel model) { String[] result = new String[0]; if (ModelState.IsValid) { try { if (model.FormFile != null && model.FormFile.Length > 0) { using (MemoryStream stream = new MemoryStream()) { await model.FormFile.CopyToAsync(stream); // Get enum BarcodeType from ComboBox selected index. BarcodeType barcodeType = (BarcodeType)model.SelectedTypeIndex; result = BarcodeScanner.Scan(stream, barcodeType); } } else throw new Exception("No Upload File."); } catch (Exception) { result = new String[0]; } } ShowResultViewModel showViewModel = new ShowResultViewModel(); showViewModel.DataMessages = result; return View(showViewModel); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
6. It is done. Now press "Ctrl+F5" to run the project.
It launches the Kestrel server and opens the default browser.
Use Choose File button to open an image file from the local system; and then, press "Scan Image" button to submit the form to server.
And the scanned bacode results would be shown in the "ShowResult" view as below.
Conclusion
The step-by-step tutorial above demonstrates that you can easily enable your ASP.NET Core MVC web app with barcode reading features using C#.
You can also quickly add more QR Code and barcode reading functions using C# barcode reader library in your ASP.NET Core project. View more details at: How to read barcodes using C# barcode reader library?
You can also quickly add more QR Code and barcode reading functions using C# barcode reader library in your ASP.NET Core project. View more details at: How to read barcodes using C# barcode reader library?
Common Asked Questions
How to enable a barcode scanner in ASP.NET Core MVC application?
To integrate a barcode image scanner feature in an C# ASP.NET Core MVC web app, you can
generate a new ASP.NET project using Visual Studio, install the OnBarcode C# Barcode Reader library with other
NuGet packages, add C# codes to handle barcode image uploading, and barcode scanning using barcode SDK APIs.
How to read 2d, 1d barcodes from various image formats?
Using C# Barcode Reader library, you can scan and read barcodes from multiple raster image formats,
including jpeg, png, bitmap, gif, multi-page tiff image file in your ASP.NET MVC web applications.
Using C# Barcode library and other 3rd party free component, you can also read and
extract barcode data from Adobe PDF, Microsoft Word, Excel, PowerPoint documents.
What platforms can I run the C# Barcode Reader library for barcode scanning?
OnBarcode C# Barcode Scanner library supports multiple .NET platforms, including
ASP.NET Web Forms, Blazor web applications, Console, Windows Forms, WPF and MAUI on desktop,
Xamarin & MAUI on mobile apps using C#, VB.NET and F#.
How to upload barcode image files for barcode scanning in ASP.NET Core web app?
In ASP.NET MVC project, you can set up a MVC controller to receive uploading image files in web page,
and use C# Barcode Scanner library to read, scan and extract barcode data from uploaded image files in C# ASP.NET MVC web app.
Is it possible to scan barcodes from video feeds using C#?
Yes. You can easily build a real time image data processing web app and scan barcodes from video feeds in your ASP.NET Core MVC web application.
Can I print and customize barcode generation in ASP.NET Core?
OnBarcode C# Barcode Reader library supports barcode scanning and recognition from image files in C# projects.
OnBarcode also provides C# Barcode Generator library, which supports printing and customization barcode generation in ASP.NET Core MVC web app.
What barcode formats are supported in Barcode Reader SDK?
OnBarcode C# Barcode Reader library supports QR Code, Data Matrix and PDF417 2d barcodes, and
Code 128, Code 39, EAN/UPC, GS1-128, ITF14 1d barcodes, and AustraliaPost, Intelligent Mail and other mail barcodes.
What license options are available for C# Barcode Reader library?
OnBarcode C# Barcode Reader library offers free trial license with full features included. You can download the free trial package
from OnBarcode website or download the nuget package with name OnBarcode.Barcode.Reader.
C# developers should replace the licnesed dll with the trail dll in the ASP.NET project.