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#
Prerequisites
Top
Download and install the following software on your computer
- Visual Studio 2022
- .NET 6.0 SDK
- 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
- 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 "OnBarcode.QRCodeGenerator.ASPNETCoreMVCDemo".
- Select .NET 6.0 (Long-term support), uncheck Configure for HTTPS, and then press Create
- Now, all auto-generated files could be found in the solution explorer.
Step 2: Install SkiaSharp
- Right-click Dependencies in the Solution Explorer, and select Manage NuGet Packages.
- Select "Browse" and use the search control to find SkiaSharp from the package source nugget.org.
- Choose the latest stable version to install SkiaSharp.
- Check Packages in the Solution Explorer to ensure the installation is completed.
Step 3: Install OnBarcode QR Code Generator DLL
- 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: </td>
<td>
<input type="text" id="tb1" name="tbMessage" style="width: 300px; " asp-for=@ViewData["Message"] />
</td>
</tr>
<tr>
<td align="right">Width (inch): </td>
<td>
<input type="text" id="tb2" name="tbWidth" style="width: 300px; " asp-for=@ViewData["Width"] />
</td>
</tr>
<tr>
<td align="right">Resolution (dpi): </td>
<td>
<input type="text" id="tb3" name="tbResolution" style="width: 300px; " asp-for=@ViewData["Resolution"] />
</td>
</tr>
<tr>
<td align="right">Fore Color: </td>
<td>
<input type="text" id="tb4" name="tbForeColor" style="width: 300px; " asp-for=@ViewData["ForeColor"] />
</td>
</tr>
<tr>
<td align="right">Back Color: </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.