How to generate barcode in C# ASP.NET Core
MVC web app?

Tutorial How-to Guide for QR Code and barcode image generation in ASP.NET Core MVC web application

Generate 2d barcode QR Code images in Visual C# .NET with complete sample C# source code







In this C# ASP.NET tutorial page, you will learn how to generate QR Code barcode images in ASP.NET Core MVC (Model-View-Controller) web application using C# code.

  • Step by step guide to create ISO standard QR Code in browser in ASP.NET Core MVC app
  • Detailed sample web app to create high resolution QR Code with specific dimension side, module color, background color
  • Easy to extent the sample application for more QR Code generation features: such as GS1 QR Code generation.
  • Support .NET 8, 7, 6, 5, .NET Core 3.1, 2.1

How to create QR Code barcodes in ASP.NET Core MVC using C#

  1. Download .NET QR Code Barcode Generator SDK
  2. Install C# library to create QR Code images in .NET projects
  3. Step by Step Tutorial





























Prerequisites

Top
Download and install the following software on your computer
  1. Visual Studio 2022
  2. .NET 6.0 SDK
  3. OnBarcode.Barcode.Common.Skia.dll




Create a new ASP.NET Core MVC web app with QR Code generation on web page using C#

Top

Step 1: Create a new ASP.NET Core MVC web app



  1. Start Visual Studio 2022 and select Create a new project

  2. Select ASP.NET Core Web App (Model-View-Controller) in the dialog, and then press Next button.

  3. Create a new project with name "OnBarcode.QRCodeGenerator.ASPNETCoreMVCDemo".

  4. Select .NET 6.0 (Long-term support), uncheck Configure for HTTPS, and then press Create

  5. Now, all auto-generated files could be found in the solution explorer.


Step 2: Install SkiaSharp & C# Barcode Generator library



Install SkiaSharp NuGet Package

  1. Right-click Dependencies in the Solution Explorer, and select Manage NuGet Packages.

  2. Select "Browse" and use the search control to find SkiaSharp from the package source nugget.org.

  3. Choose the latest stable version to install SkiaSharp.

  4. Check Packages in the Solution Explorer to ensure the installation is completed.






Install OnBarcode Barcode Generator DLL

  1. Add DLL reference "OnBarcode.Barcode.Common.Skia.dll".





Step 3.1: Add C# source code to Controller

Copy all following codes to replace the content of the file HomeController.cs
using Microsoft.AspNetCore.Mvc;
using OnBarcode.QRCodeGenerator.ASPNETCoreMVCDemo.Models;
using System.Diagnostics;

namespace OnBarcode.QRCodeGenerator.ASPNETCoreMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        //  Cannot be empty.
        private static String tbMessage = "QRCode";
        //  Must be a positive float value less than 10.
        private static String tbWidth = "2";
        //  Must be a positive int value less than 1200.
        private static String tbResolution = "300";
        //  Hex String: from 0 to FFFFFF
        private static String tbForeColor = "000000";
        //  Hex String: from 0 to FFFFFF
        private static String tbBackColor = "FFFFFF";

        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //  Set default value to text box.
            ViewData["Message"] = tbMessage;
            ViewData["Width"] = tbWidth;
            ViewData["Resolution"] = tbResolution;
            ViewData["ForeColor"] = tbForeColor;
            ViewData["BackColor"] = tbBackColor;
            return View();
        }

        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 Task<IActionResult> Show()
        {
            try
            {
                //  Update backup 
                tbMessage = Request.Form["tbMessage"].ToString();
                tbWidth = Request.Form["tbWidth"].ToString();
                tbResolution = Request.Form["tbResolution"].ToString();
                tbForeColor = Request.Form["tbForeColor"].ToString();
                tbBackColor = Request.Form["tbBackColor"].ToString();

                byte[] dataBytes = tryToCreateBarcode();
                if (dataBytes == null || dataBytes.Length == 0)
                    throw new Exception("fail to create barcode");
                ViewData["BarcodeImage"] = System.Convert.ToBase64String(dataBytes);

                ViewData["ViewResult"] = "SUCCESS";
                return Task.FromResult<IActionResult>(View());
            }
            catch (Exception)
            {
                //return Task.FromResult<IActionResult>(RedirectToAction(nameof(Index)));
                ViewData["ViewResult"] = "FAILED";
                return Task.FromResult<IActionResult>(View());
            }
        }

        //  Create barcode. Return empty array if failed.
        private byte[] tryToCreateBarcode()
        {
            try
            {
                if (String.IsNullOrEmpty(tbMessage))
                    throw new Exception("Message cannot be null or empty.");
                int resolution = Convert.ToInt32(tbResolution);
                if (resolution > 1200)
                    throw new Exception("Resolution out of range.");
                float width = Convert.ToSingle(tbWidth);
                if (width > 10F)
                    throw new Exception("Width out of range.");
                //  Hex String: RRGGBB
                uint rgbForeColor = Convert.ToUInt32(tbForeColor, 16) & 0xFFFFFF;
                //  Hex String: RRGGBB
                uint rgbBackColor = Convert.ToUInt32(tbBackColor, 16) & 0xFFFFFF;

                OnBarcode.Barcode.QRCode qrcode = new OnBarcode.Barcode.QRCode();
                qrcode.DataMode = Barcode.QRCodeDataMode.Auto;
                qrcode.Data = tbMessage;
                qrcode.UOM = Barcode.UnitOfMeasure.INCH;

                qrcode.Resolution = resolution;
                qrcode.BarcodeWidth = width;
                qrcode.BarcodeHeight = width;
                qrcode.ForeColor = new SkiaSharp.SKColor(0xFF000000 + rgbForeColor);
                qrcode.BackColor = new SkiaSharp.SKColor(0xFF000000 + rgbBackColor);

                qrcode.AutoResize = true;
                qrcode.ImageFormat = SkiaSharp.SKEncodedImageFormat.Png;
                return qrcode.drawBarcodeAsBytes();
            }
            catch (Exception)
            {
                return new byte[0];
            }
        }
    }
}




Step 3.2: Add C# source code to Views

Copy all following codes to replace the content of the file Index.cshtml
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <br />
    <form asp-action="Show">
        <table align="center">
            <tbody>
                <tr>
                    <td align="right">Data Message: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb1" name="tbMessage" style="width: 300px; " asp-for=@ViewData["Message"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Width (inch): &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb2" name="tbWidth" style="width: 300px; " asp-for=@ViewData["Width"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Resolution (dpi): &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb3" name="tbResolution" style="width: 300px; " asp-for=@ViewData["Resolution"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Fore Color: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb4" name="tbForeColor" style="width: 300px; " asp-for=@ViewData["ForeColor"] />
                    </td>
                </tr>
                <tr>
                    <td align="right">Back Color: &nbsp;&nbsp;</td>
                    <td>
                        <input type="text" id="tb5" name="tbBackColor" style="width: 300px; " asp-for=@ViewData["BackColor"] />
                    </td>
                </tr>
            </tbody>
        </table>
        <br />
        <input type="submit" value="Show" />
        <br />
        <br />
    </form>
</div>




Add a new View Show.cshtml to display the generated QR Code image in browser.

Contents of Show.cshtml

@{
    ViewData["Title"] = "Show";
}

<h1>Show Barcode - @ViewData["ViewResult"]</h1>
<div style="display:flex;justify-content:center">
    <a asp-action="Index">Back to Index</a>
</div>
<br />
<div style="display:flex;justify-content:center">
    <img src="data:image/png;base64,@ViewData["BarcodeImage"]" />
</div>






Step 4: Run the web app

It is done. Now press "Ctrl+F5" to run the project.





You will view the app running in the browser. Click button Show to generate QR Code barcode image.





Enable converting Unicode text to QR Code in C# ASP.NET Core MVC app

Top
You can easily enable generating QR Code with Unicode text encoded in the ASP.NET Core MVC web app.

Add the following C# code to tryToCreateBarcode() method in class HomeController
qrcode.EncodeUnicodeText = true;
When EncodeUnicodeText option is true, you can keyin Unicode text in the "Data Message" text box on the web browser, and the barcode library will automatically convert the Unicode text to QR Code, and display the printed QR Code on the web page.

By default the C# barcode library will create QR Code with Unicode text encoded in UTF8 encode. If you need other text encode, you can use the property UnicodeEncoding to change the text encode, view the C# code below for details.
qrcode.UnicodeEncoding = TextEncoding.UTF8;




Customize and add logo image on QR Code in C# ASP.NET Core MVC app

Top
Now more and more business activities will use QR Code to promote product or service. They usually want to add the company logo on the printed QR Code.

Here we will demostrate how to create QR Code with logo image printed in the above C# ASP.NET Core MVC web application.

Using C# Barcode Generator library, you can quickly create QR Code with logo image printed on the center of the barcode.

  • Set Logo property with the logo image object in "System.Drawing.Bitmap" format
  • Specify the logo image displaying rectangle area through LogoActualSize property
qrcode.Logo = new System.Drawing.Bitmap("company-logo.png");
qrcode.LogoActualSize = new System.Drawing.SizeF(600, 600);
The above C# sample code should be inserted into tryToCreateBarcode() method in HomeController class in the ASP.NET MVC app.

After running the ASP.NET Core MVC app, you will find that all generated QR Codes on the web page will be printed a logo image on the center of the QR Codes.




Scan and verify the generated QR Code image label in C# ASP.NET Core MVC app

Top
You may need verify the printed QR Code image on the ASP.NET Core web page. OnBarcode also provides mature C# Barcode Reader library to scan and read the QR Code data message from image files.

You can easily download and install the barcode reader library and start to scan, verify your generated QR Code images.
using OnBarcode.Barcode.BarcodeScanner;

string[] datas = BarcodeScanner.Scan("qrcode-sample.png", BarcodeType.QRCode);
BarcodeDetail[] datasInDetail = BarcodeScanner.ScanInDetails("qrcode-sample.png", BarcodeType.QRCode);
Using the above C# code, you can quickly scan an image with QR Codes, and read all QR Codes data with detailed information from the image file. You will get the QR Code data message, barcode detected location area, rotation angle information from the scanned BarcodeDetail objects.
















OnBarcode is a market-leading provider of barcode imaging generator, reader controls and components for ASP.NET, Windows Forms, WPF, as well Java, Android, iOS (iPhone, iPad) across all major enterprise development platforms. We provides comprehensive tutorials and how-tos for various linear, 2d barcode information, such as C# in ASP.NET, C# .NET, C# Barcode Encoding, C# Barcode Image, VB.NET in ASP.NET, VB.NET Winforms, VB.NET Barcode Encoding. OnBarcode barcode products are supported by RasterEdge ASP.NET Document Viewer, which supports ASP.NET PDF Viewer, ASP.NET MVC Document Viewer, ASP.NET PDF Editor, MVC PDF Viewer. And provide high quality C# Convert PDF to Tiff, C# Convert PDF to Word, C# Convert PDF to HTML, C# Convert PDF to Jpeg images, and their easy and simple documents, like C# PDF SDK, C# extract text from PDF, C# Compress PDF, Print PDF in C# and C# extract image from PDF.
Terms of Use | Privacy Policy
Copyright © OnBarcode.com . All rights reserved.