Test in a live environment
Test in production without watermarks.
Works wherever you need it to.
QR codes have become an integral part of modern technology, offering a convenient way to store and transmit information. In web development, QR code generators like the one we'll implement using IronQR in ASP.NET Core, provide robust capabilities for dynamic QR code creation. QR code generators are invaluable for various applications such as ticketing systems, authentication, inventory management, and more. This article delves into the process of creating QR codes in ASP.NET Core using IronQR, a powerful library designed for this purpose. ASP.NET Core, being a versatile framework for building web applications, offers robust capabilities for generating QR codes. In this article, we'll delve into the process of creating QR codes in ASP.NET Core using IronQR, a powerful library for QR code generation from Iron Software.
IronQR is a high-performance QR code generation library for .NET applications. It provides a simple and intuitive API for generating QR codes with various customization options. IronQR supports .NET Standard, making it compatible with a wide range of platforms, including ASP.NET Core. With IronQR, developers can effortlessly generate QR codes with different data types, error correction levels, sizes, and formats.
IronQR enables you to generate and read QR codes with ease. Whether you need to create QR codes dynamically or extract information from existing ones, this library has you covered.
The library provides a user-friendly API that allows developers to integrate barcode functionality into their .NET projects quickly. You can start working with QR codes in just a few minutes.
IronQR supports various .NET versions, including:
It covers a wide range of project types, including web (Blazor & WebForms), mobile (Xamarin & MAUI), desktop (WPF & MAUI), and console applications.
IronQR uses an advanced custom Machine Learning model to detect QR codes. This ensures accurate and reliable code recognition. Additionally, there’s a Slim Mode option (non-ML) available for those who prefer a lightweight approach.
You can read QR codes from various image formats, including:
System.Drawing
BitmapsAnyBitmap
)IronQR allows you to write QR codes for different document types, such as:
System.Drawing
ImagesMemoryStream
, byte[]
)Customize QR codes by Resizing, Adjusting margins and borders, Recoloring, Adding logos
IronQR provides detailed error messages and supports custom QR error correction levels.
With this knowledge, let's get started with the application to generate QR code in ASP.NET Core.
Before we dive into QR code generation, let's set up a new ASP.NET Core project. Here are the steps to initiate a new project:
Start by creating a new project in Visual Studio and selecting ASP.Net Core Web App application template
Provide Project Name and location
Select the required .NET version.
Click the "create" button to generate the application code from the template
Install IronQR library from Visual Studio Package Manager as shown below.
IronQR can also be installed using NuGet Package Manager.
Now, let's create a QR code app.
QRCode
Modelusing System.ComponentModel.DataAnnotations;
namespace GenerateQRCode.Models
{
public class QRCodeModel
{
[Display(Name = "Enter QR Code Text")]
public string QRCodeText
{
get;
set;
}
}
}
using System.ComponentModel.DataAnnotations;
namespace GenerateQRCode.Models
{
public class QRCodeModel
{
[Display(Name = "Enter QR Code Text")]
public string QRCodeText
{
get;
set;
}
}
}
Imports System.ComponentModel.DataAnnotations
Namespace GenerateQRCode.Models
Public Class QRCodeModel
<Display(Name := "Enter QR Code Text")>
Public Property QRCodeText() As String
End Class
End Namespace
To add a new controller, right-click on the controller folder and provide a name as shown below.
Select the Empty Controller.
Provide a name.
Next, integrate the following code into the controller.
using GenerateQRCode.Models;
using IronQr;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace GenerateQRCode.Controllers
{
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
// Create a QR Code object
QrCode myQr = QrWriter.Write(generateQRCode.QRCodeText);
// Save QR Code as a Bitmap
AnyBitmap qrImage = myQr.Save();
// Save QR Code Bitmap as File
qrImage.SaveAs(filePath);
string fileName = Path.GetFileName(filePath); // qr code file
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
}
}
using GenerateQRCode.Models;
using IronQr;
using IronSoftware.Drawing;
using Microsoft.AspNetCore.Mvc;
namespace GenerateQRCode.Controllers
{
public class QrCodeController : Controller
{
private readonly IWebHostEnvironment _environment;
public QrCodeController(IWebHostEnvironment environment)
{
_environment = environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
// Create a QR Code object
QrCode myQr = QrWriter.Write(generateQRCode.QRCodeText);
// Save QR Code as a Bitmap
AnyBitmap qrImage = myQr.Save();
// Save QR Code Bitmap as File
qrImage.SaveAs(filePath);
string fileName = Path.GetFileName(filePath); // qr code file
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
}
}
Imports GenerateQRCode.Models
Imports IronQr
Imports IronSoftware.Drawing
Imports Microsoft.AspNetCore.Mvc
Namespace GenerateQRCode.Controllers
Public Class QrCodeController
Inherits Controller
Private ReadOnly _environment As IWebHostEnvironment
Public Sub New(ByVal environment As IWebHostEnvironment)
_environment = environment
End Sub
Public Function Index() As IActionResult
Return View()
End Function
<HttpPost>
Public Function CreateQRCode(ByVal generateQRCode As QRCodeModel) As IActionResult
Try
Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png")
' Create a QR Code object
Dim myQr As QrCode = QrWriter.Write(generateQRCode.QRCodeText)
' Save QR Code as a Bitmap
Dim qrImage As AnyBitmap = myQr.Save()
' Save QR Code Bitmap as File
qrImage.SaveAs(filePath)
Dim fileName As String = System.IO.Path.GetFileName(filePath) ' qr code file
Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}" & "/GeneratedQRCode/" & fileName
ViewBag.QrCodeUri = imageUrl
Catch e1 As Exception
Throw
End Try
Return View()
End Function
End Class
End Namespace
The code starts with using statements, which import necessary namespaces. The GenerateQRCode.Controllers
namespace contains the QrCodeController
class.
The QrCodeController
class has a constructor that takes a IWebHostEnvironment
parameter. This parameter is injected by ASP.NET Core for handling web hosting-related tasks.
Index()
: This method returns a view (presumably an HTML page) when accessed. It doesn’t seem to be directly related to QR code generation. CreateQRCode(QRCodeModel generateQRCode)
: This method is the heart of the QR code generation logic. It receives a QRCodeModel
object (presumably containing the QR code text) as a parameter.
It constructs a path for saving the generated QR code image. Creates a QR code object using QrWriter.Write(generateQRCode.QRCodeText)
. Saves the QR code as a bitmap image. Constructs an image URL based on the web request details. Sets the ViewBag.QrCodeUri
property with the image URL. If any exceptions occur during this process, they are thrown.
The actual QR code generation happens within the CreateQRCode
method. The QrWriter.Write(generateQRCode.QRCodeText)
call creates a QR code object based on the provided text.
The generated QR code is saved as a bitmap image using qrImage.SaveAs(filePath)
. The image file path is constructed based on the web root path and the desired file name.
The imageUrl
is constructed using the web request’s scheme, host, and path base. This URL points to the location where the generated QR code image can be accessed. Overall, this controller handles QR code generation, saving the image, and providing an image URL for further use
To add a new view, right-click the CreateQRCode
action method in the QrCodeController
class.
Select "Add View" then select "Razor View". Click on the "Add" button.
Then select the "Create" template and Model class generated previously.
Now replace the below code in the view
@model GenerateQRCode.Models.QRCodeModel
@{
ViewData["Title"] = "Generate QR Code";
}
<h1>Generate QR Code</h1>
<h4>QRCodeModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateQRCode">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="QRCodeText" class="control-label"></label>
<span asp-validation-for="QRCodeText" class="text-danger"></span>
</div>
<div class="form-group">
</div>
<div class="form-group">
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Clear</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
@model GenerateQRCode.Models.QRCodeModel
@{
ViewData["Title"] = "Generate QR Code";
}
<h1>Generate QR Code</h1>
<h4>QRCodeModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateQRCode">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="QRCodeText" class="control-label"></label>
<span asp-validation-for="QRCodeText" class="text-danger"></span>
</div>
<div class="form-group">
</div>
<div class="form-group">
<img src="@ViewBag.QrCodeUri" class="img-thumbnail" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Clear</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
model ReadOnly Property () As GenerateQRCode.Models.QRCodeModel
ViewData("Title") = "Generate QR Code"
End Property
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> <div> <a asp-action="Index"> Clear</a> </div> @section Scripts
"img-thumbnail" /> </div> </form> </div> </div> (Of div) <a asp-action="Index"> Clear</a> </div> section Scripts
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> <div> <a asp-action
"@ViewBag.QrCodeUri" class="img-thumbnail" /> </div> </form> </div> </div> (Of div) <a asp-action
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> </div> <div class="form-group"> <img src="@ViewBag.QrCodeUri" class
"form-group"> <img src="@ViewBag.QrCodeUri" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> </div> <div class="form-group"> <img src
"form-group"> </div> <div class="form-group"> <img src
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> </div> <div class
"text-danger"></span> </div> <div class="form-group"> </div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class
"QRCodeText" class="text-danger"></span> </div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for="QRCodeText" class
"control-label"></label> <span asp-validation-for="QRCodeText" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class="control-label"></label> <span asp-validation-for
"QRCodeText" class="control-label"></label> <span asp-validation-for
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="QRCodeText" class
"form-group"> <label asp-for="QRCodeText" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for
"text-danger"></div> <div class="form-group"> <label asp-for
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class
"ModelOnly" class="text-danger"></div> <div class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary="ModelOnly" class
"CreateQRCode"> <div asp-validation-summary="ModelOnly" class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary
"col-md-4"> <form asp-action="CreateQRCode"> <div asp-validation-summary
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: Private Private Private Private Private Private Private Private Private Private Private Private Friend <h1> Generate QR Code</h1> <h4> QRCodeModel</h4> <hr /> <div Class="row"> <div class="col-md-4"> <form asp-action
"row"> <div class="col-md-4"> <form asp-action
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Private Private Private Private Private Private Private Private Private Private Private Private Private Private Friend (Of h1) Generate QR Code</h1> (Of h4) QRCodeModel</h4> <hr /> <div Class="row"> <div class
@
If True Then
Await Html.RenderPartialAsync("_ValidationScriptsPartial")
End If
End Class
Do the same for the index action method also, so that when the app is launched, it will not throw an error for the POST request.
Now in the program.cs change the following code to make the above view as default route.
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}"
);
app.MapControllerRoute(
name: "default",
pattern: "{controller=QrCode}/{action=Index}"
);
app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=Index}")
This action will modify the default route from HomeController
to our QrCode
Controller.
Now, Compile and run the project.
Enter any text in the text box and click 'Create.' This will create a new QR code as shown below.
QrStyleOptions
are used to style the QR code generation.
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
// Create a QR Code obj
QrCode qrCode = QrWriter.Write(generateQRCode.QRCodeText);
QrStyleOptions style = new QrStyleOptions
{
Dimensions = 300, // px
Margins = 10, // px
Color = Color.YellowGreen
};
// Save QR Code as a any bitmap
AnyBitmap qrImage = qrCode.Save(style);
// Save QR Code Bitmap to File
qrImage.SaveAs(filePath);
string fileName = Path.GetFileName(filePath); // qr code file
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
[HttpPost]
public IActionResult CreateQRCode(QRCodeModel generateQRCode)
{
try
{
string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string filePath = Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png");
// Create a QR Code obj
QrCode qrCode = QrWriter.Write(generateQRCode.QRCodeText);
QrStyleOptions style = new QrStyleOptions
{
Dimensions = 300, // px
Margins = 10, // px
Color = Color.YellowGreen
};
// Save QR Code as a any bitmap
AnyBitmap qrImage = qrCode.Save(style);
// Save QR Code Bitmap to File
qrImage.SaveAs(filePath);
string fileName = Path.GetFileName(filePath); // qr code file
string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}" + "/GeneratedQRCode/" + fileName;
ViewBag.QrCodeUri = imageUrl;
}
catch (Exception)
{
throw;
}
return View();
}
<HttpPost>
Public Function CreateQRCode(ByVal generateQRCode As QRCodeModel) As IActionResult
Try
Dim path As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode")
If Not Directory.Exists(path) Then
Directory.CreateDirectory(path)
End If
Dim filePath As String = System.IO.Path.Combine(_environment.WebRootPath, "GeneratedQRCode/qrcode.png")
' Create a QR Code obj
Dim qrCode As QrCode = QrWriter.Write(generateQRCode.QRCodeText)
Dim style As New QrStyleOptions With {
.Dimensions = 300,
.Margins = 10,
.Color = Color.YellowGreen
}
' Save QR Code as a any bitmap
Dim qrImage As AnyBitmap = qrCode.Save(style)
' Save QR Code Bitmap to File
qrImage.SaveAs(filePath)
Dim fileName As String = System.IO.Path.GetFileName(filePath) ' qr code file
Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}" & "/GeneratedQRCode/" & fileName
ViewBag.QrCodeUri = imageUrl
Catch e1 As Exception
Throw
End Try
Return View()
End Function
For developers who want to test out IronQR, a trial license is available here. This license key needs to be placed in the appSettings.json file. Doing so will remove the watermark shown in the images above. This will remove the watermark shown in the images above.
{
"IronQR.License.LicenseKey" : "My key"
}
In this article, we've explored how to generate QR codes in ASP.NET Core using IronQR. By leveraging the power of IronQR, developers can easily integrate QR code generation functionality into their web applications. Whether it's for ticketing, authentication, or information sharing, QR codes offer a versatile solution for transmitting data efficiently. With IronQR, creating and customizing QR codes in ASP.NET Core has never been easier. Start incorporating QR code generation into your ASP.NET Core projects and unlock a world of possibilities for dynamic data encoding and sharing.
9 .NET API products for your office documents