How to generate QR Code in C# ASP.NET Core MVC?

Integration & Developer Guide for QR Code 2D 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

  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.






Step 3: Install OnBarcode QR Code Generator DLL

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





Step 4.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 4.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 5: 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.

















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.