Prerequisites
Download and install the following software on your computer
- Visual Studio 2022
- .NET 6.0 SDK
- OnBarcode.Barcode.Common.Skia.dll
Create new ASP.NET Core MVC web app with QR Code generation
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 & C# Barcode Generator library
Install SkiaSharp NuGet Package
- 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.
Install OnBarcode Barcode Generator DLL
- 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: </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
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.
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
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
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.
Add the following C# code to tryToCreateBarcode() method in class HomeController
qrcode.EncodeUnicodeText = true;
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
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.
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.
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);
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
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 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.
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);
