This C# tutorial provides a step by step guide for building an ASP.NET Core MVC app project, where user can upload an image file with barcode and scan, read the barcode data message from it.
After this tutorial, you will be albe to
- Read QR Code and other 20+ barcodes data from images in ASP.NET Core MVC (Model-View-Controller) web app using C#.
- Support both System.Drawing.Common for Windows and SkiaSharp for Linux, MacOS
- Support .NET 7, 6, 5 and .NET Core 3.1, 2.1 ASP.NET Core web application
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.
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.
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".
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".
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.
@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.
@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.
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.
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?