C# Barcode Reader > C# Barcode Scanner Tutorial > How to scan, read barcode in C# ASP.NET Core MVC web application using C# Barcode Reader library?

How to scan, read barcode in C# ASP.NET Core MVC web app?

Detailed tutorial for reading and scanning barcode image in C# ASP.NET MVC (Model-View-Controller) web app

C# Barcode Reader Library

Scan QR Code, Data Matrix, Code 128, GS1, EAN/UPC from image files in ASP.NET Core MVC web app.

Download Now
NuGet Ready
.NET 5+
.NET Framework 4.x, 3.x, 2.x




How to read barcodes from image regsions of interest in MVC?

When using the C# ASP.NET MVC barcode reader library, you can improve barcode scanning speed by scanning only specific image regions.

The following C# code uses barcodelib barcode SDK to define a narrow scan region, attach it to EAN-13 barcode optimization settings, read a PNG image file, and enumerate decoded EAN13 barcode messages.

  • Create a rectangular scan area in ScanArea object from the top-left point to a bottom-right point, effectively limiting decoding to the top 20% of the image.
ScanArea top20 = new ScanArea(new PointF(0.0F, 0.0F), new PointF(100.0F, 20.0F));
List<ScanArea> areas = new List<ScanArea>();
areas.Add(top20);

OptimizeSetting setting = new OptimizeSetting(BarcodeReader.EAN13);
setting.setAreas(areas);
BarCode[] datas = BarcodeReader.ReadBarcode("barcode-sample.png", setting);
foreach (BarCode aBarcode in datas)
{
    String data = aBarcode.GetMessage();
}
Note: Barcodes will not be recognized if they fall outside the specified region of the image.
You can view more details about image regions definiton and barcode scanning here:
How to scan, read barcodes from specified image regions using C#?




How to scan, detect barcodes with different types from a single image file in ASP.NET Core MVC?

When using the BarcodeLib C# Barcode Reader library, you can recognize multiple barcode symbologies on a single image simultaneously, such as Code 128 and EAN-13. This helps scan and read all different barcode types in less time.

The C# sample code below configures the barcode SDK to decode multiple symbologies, specifically CODE128 and EAN13, and then reads a PNG sample image file and enumerates the decoded message texts.

OptimizeSetting options = new OptimizeSetting(
    new int[] {
        BarcodeReader.CODE128,
        BarcodeReader.EAN13});
BarCode[] datas = BarcodeReader.ReadBarcode(
    "multiple-barcode-types-scanning-sample.png", options);
foreach (BarCode aBarcode in datas)
{
    string barcodeText = aBarcode.GetMessage();
}
Note: Reading and recognizing multiple types of barcode may cause re-miscognition. Learn more details here:
How to scan, read multiple barcodes from image file using C# barcode reader library?




How to scan barcode using different directions in C# ASP.NET MVC app?

If your barcodes have a fixed orientation in the image, for example, all printed horizontally top-to-bottom, customizing the scanning direction of the barcode reader can improve barcode scanning speed.

Here we configure the barcode reader to decode only CODE128 symbology and restricts the read-direction order to top-to-bottom.
  • Call method setReadDirectionOrder() to specify the image scanning directions.
    Here set the decoding direction order to top-to-bottom only. If the barcode is rotated, upside down, or scanned bottom-to-top, decoding may fail. Consider using multiple directions when input orientation is not guaranteed.
    By default, the barcode scanner SDK will scan all four directions on the barcode image.
OptimizeSetting setting = new OptimizeSetting(BarcodeReader.CODE128);
setting.setReadDirectionOrder(new int[] {
    BarcodeReader.DIRECTION_TOP_TO_BOTTOM
});
BarCode[] datas = BarcodeReader.ReadBarcode("barcode-sample.png", setting);
foreach (BarCode aBarcode in datas)
{
    String data = aBarcode.GetMessage();
}




How to scan, read Unicode text from 2d barcodes in C# ASP.NET app?

2D barcodes (e.g. QR Code, Data Matrix, PDF417) can convert Unicode text into 2D barcodes via binary data. When the ASP.NET barcode reader library decodes such 2D barcodes, it is important to use the same data encoding mode as the barcode encoder.

  • Call method GetMessage() to decode and parse Unicode text from 2d barcodes.
OptimizeSetting options = new OptimizeSetting(
    new int[] {
        BarcodeReader.DATAMATRIX,
        BarcodeReader.PDF417});
BarCode[] datas = BarcodeReader.ReadBarcode("2d-barcodes-unicode-text-sample.png", options);
foreach (BarCode aBarcode in datas)
{
    string barcodeUnicodeText = aBarcode.GetMessage();
}
Note: The C# Barcode Scanner uses UTF-8 by default to decode and convert binary data to Unicode text. UTF-8 is the most commonly used encoding mode for 2D barcodes (QR Code, Data Matrix). If the barcode generator uses a different encoding mode, the barcode scanner must use the same encoding for decoding. You can use the following .NET API to specify the encoding.
public string GetMessage(Encoding enc)

Learn more details about 2d barcode unicode text decoding here:
How to scan, decode 2d barcode with unicode text using C# Barcode Reader library?




How to scan, read barcode images in C# ASP.NET Core MVC web app?

Here we will step-by-step explain how to scan, read barcode images in C# ASP.NET Core web app using BarcodeLib C# Barcode Reader library. By the end of this tutorial, you will get a simple ASP.NET Core MVC web application with barcode scanner feature enabled.





1. Create a new ASP.NET Core MVC web project

  1. Start Visual Studio 2022 and choose Create a new project.
  2. Select ASP.NET Core Web App (Model-View-Controller) in the dialog, and then press Next button.
  3. In "Configure your new project" dialog, create a new project with name BarcodeLib.BarcodeReader.AspNetCore.MVC.Demo. Click Next button.
  4. Choose Framework as .NET 8.0 (Long Term Support), and Click Create.
  5. Now we have created a new ASP.NET Core MVC web project successfully.




2. Add Barcode Scanner library

Add the following Barcode Reader library dll and nuget package to the ASP.NET Core MVC web project.
  • Add barcode reader library .net standard dll BarcodeLib.BarcodeReader.Common.dll to the project reference
  • Search and install nuget System.Drawing.Common (latest stable version) from NuGet Package Manager in Visual Studio




3. Add C# data model classes to the ASP.NET Core MVC project

  1. Right-click the Models folder in the Solution Explorer and choose Add > Class... to open the Add New Item dialog.
  2. Then add a class item with name IndexViewModel.cs.
  3. Add the following C# codes to class IndexViewModel.cs.

    namespace BarcodeLib.BarcodeReader.AspNetCore.MVC.Demo.Models
    {
        public class IndexViewModel
        {
            public List<String> BarcodeTypes { get; set; } = new List<String> {
                "Codabar", "Code 128 / GS1-128", "Code 39", "Code 39 Full ASCII",
                "Interleaved 2 of 5", "EAN-13", "EAN-8",
                "UPC-A", "UPC-E", "QR Code", "PDF-417",
                 "Data Matrix", "IDENTCODE", "Code 93", "Patch Code",
                "POSTNET","PLANET","RM4SCC", "Australia Post",
                "Intelligent Mail (OneCode)"
            };
            public int SelectedTypeIndex { get; set; }
            public IFormFile? FormFile { get; set; }
        }
    }
    
  4. Then add a new class item with name ShowResultViewModel.cs.
  5. Add the following C# codes to class ShowResultViewModel.cs.

    namespace BarcodeLib.BarcodeReader.AspNetCore.MVC.Demo.Models
    {
        public class ShowResultViewModel
        {
            public String? BarcodeImagebase64 { get; set; }
            public String[]? DataMessages { get; set; }
        }
    }
    




4. Add Views to the ASP.NET Core MVC project

View : Index

Select and open view file Index.cshtml and replace ALL content by following codes.

@model IndexViewModel;
@{
    ViewData["Title"] = "BarcodeLib C# Barcode Scanner on ASP.NET Core MVC web app";
}

<div class="text-center">
    <h1>ASP.NET Core MVC Barcode Scanner<br/>Web Application</h1>
    <br/>
    <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')" />
        &nbsp;&nbsp;
        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 Barcode" disabled />
    </form>
</div>


View : ShowResult

  1. Right click the folder Views/Home, and choose Add > View....
  2. Select Razor View - Empty to open Add New Item dialog.
  3. 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">
        
        <br/><br/>
        <table name="ScanResult" class="table-borderless" style="width:70%;" align="center">
            <thead>
                <tr>
                    <td colspan="2" style="text-align:center;">
                        <h1>ASP.NET Core MVC Barcode Scanner Web Application</h1>
                        <br/><br/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        Barcode Scanning Result</td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="2" align="left">
                        <img src="data:image/png;base64,@Model.BarcodeImagebase64" 
                              alt="Scanned Barcode Image" />
                        <br/><br/>
                    </td>
                </tr>
                
                
                
                @if (Model.DataMessages != null && Model.DataMessages.Length >= 0)
                {
                    <tr>
                        <td colspan="2" align="left">
                            Number of valid barcodes:&nbsp;&nbsp;@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

  1. Adding two methods Index() and ShowResult() to class HomeController.cs.

    using BarcodeLib.BarcodeReader.AspNetCore.MVC.Demo.Models;
    using Microsoft.AspNetCore.Mvc;
    using System.Diagnostics;
    using System.IO;
    
    namespace BarcodeLib.BarcodeReader.AspNetCore.MVC.Demo.Controllers
    {
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
    
            public HomeController(ILogger<HomeController> logger)
            {
                _logger = logger;
            }
    
            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 });
            }
    
            public IActionResult Index()
            {
                IndexViewModel model = new IndexViewModel();
                model.SelectedTypeIndex = 1;
                return View(model);
            }
    
            [HttpPost]
            public async Task<IActionResult> ShowResult(IndexViewModel model)
            {
                String[] result = new String[0];
                String barcodeImageBase64 = "";
                if (ModelState.IsValid)
                {
                    try
                    {
                        if (model.FormFile != null && model.FormFile.Length > 0)
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {
                                await model.FormFile.CopyToAsync(stream);
    
    
                                barcodeImageBase64 = ConvertBarcodeImage2Base64(stream);
    
                                OptimizeSetting options = new OptimizeSetting(model.SelectedTypeIndex);
    
                                BarCode[] barcodes = BarcodeReader.ReadBarcode(stream, options);
    
                                result = new String[barcodes.Length];
                                int index = 0;
                                foreach (var barcodeInfo in barcodes)
                                {
                                    result[index] = barcodeInfo.GetMessage();
                                    index++;
                                }
                            }
                        }
                        else
                            throw new Exception("No Upload File.");
                    }
                    catch (Exception)
                    {
                        result = new String[0];
                    }
                }
    
                ShowResultViewModel showViewModel = new ShowResultViewModel();
                showViewModel.BarcodeImagebase64 = barcodeImageBase64;
                showViewModel.DataMessages = result;
                return View(showViewModel);
            }
    
            private String ConvertBarcodeImage2Base64(MemoryStream barcodeStream)
            {
                barcodeStream.Position = 0;
                byte[] imageBytes = barcodeStream.ToArray();
                return Convert.ToBase64String(imageBytes);
            }
        }
    }
    




6. Run the ASP.NET Core MVC web app in Visual Studio

Now press "Ctrl+F5" to run the project. The Visual Studio 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.

Related Barcode Library Tutorials