USING IRONBARCODE How to Generate QR Codes in ASP.NET MVC Jordi Bardia 已更新:六月 22, 2025 Download IronBarcode NuGet 下载 DLL 下载 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article In today's fast-paced digital landscape, the generation of QR codes has become an essential tool for efficient information sharing. These compact, two-dimensional barcodes, capable of storing a wide range of data, including URLs, text, contact information, product details, and much more, play a pivotal role in modern communication. Incorporating QR code generation capabilities into your ASP.NET MVC application allows you to empower users by seamlessly generating QR codes and enhancing their experience, streamlining interactions, and facilitating the effortless exchange of information. If you're developing an ASP.NET MVC application and want to incorporate QR code generation capabilities, IronBarcode is an excellent library that simplifies the process. In this article, we will explore how to generate QR codes in ASP.NET MVC using the Iron Barcode library. IronBarcode IronBarcode is a powerful and feature-rich QR Code generation and recognition library for .NET applications. With IronBarcode, developers can easily integrate barcode and QR Code functionality into their ASP.NET MVC projects, including the ability to generate QR codes. The library provides a comprehensive set of tools and APIs that simplify the process of creating and customizing QR codes, allowing developers to tailor them to their specific requirements. IronBarcode offers extensive support for various barcode types, including QR codes, making it an ideal choice for projects that require QR code generation capabilities. It provides developers with the flexibility to specify the data to be encoded, control the size and resolution of the generated QR codes, and even add visual styling elements such as colors and logos. The library ensures high-quality barcode generation with precise control over every aspect of the QR code's appearance. Beyond QR code generation, IronBarcode also includes robust features for barcode reading and decoding. It supports scanning and extracting data from QR codes, enabling applications to process information encoded within them. This functionality is beneficial for scenarios where barcode scanning and data extraction are necessary, such as inventory management, ticketing systems, and mobile applications. Now, let's create a project to generate a QR code in the ASP.NET Core MVC Web app. Setting Up the Project Before we delve into the implementation details, let's ensure that your ASP.NET MVC project is set up and ready to go. Whether you're starting a new project or working with an existing one, the steps outlined below will guide you through the process of integrating the Iron Barcode library into your application. In my case, I have created a new project. Steps for creating a new project are as follows: Open Microsoft Visual Studio 2022. On the start page, click on "Create a new project" or go to "File" > "New" > "Project" from the top menu. In the "Create a new project" window, you'll see different project templates to choose from. Choose the project template "ASP.NET Core web app (Model-view-controller)" and click "Next." Enter a name and location for your project. Choose a suitable location on your computer to save the project files. Select the desired framework version. Visual Studio usually suggests the latest stable version, but you can choose a different one if needed. I have chosen .NET 7. Customize any additional project settings, such as authentication options or project folders, based on your requirements. Click "Create" to create the project. Visual Studio will then generate the project files and open the solution explorer, where you can see the project structure and start working on your code. Now, we need to install Iron Barcode Library into our application. Install Iron Barcode To begin, open the Package Manager Console in Visual Studio and run the following command: Install-Package IronBarCode This command will install the Iron Barcode library and add the necessary references to your project. Now, let's write some code to create QR codes. Create QRCodeModel Create a Model Class inside the Models folder and write the following code: using System.ComponentModel.DataAnnotations; public class QRCodeModel { [Display(Name = "Enter QR Code Text")] public string QRCodeText { get; set; } } using System.ComponentModel.DataAnnotations; public class QRCodeModel { [Display(Name = "Enter QR Code Text")] public string QRCodeText { get; set; } } Imports System.ComponentModel.DataAnnotations Public Class QRCodeModel <Display(Name := "Enter QR Code Text")> Public Property QRCodeText() As String End Class $vbLabelText $csharpLabel Create QR Code Controller In your ASP.NET MVC project, create a new controller named QrCodeController. To do this, right-click on the Controllers folder in your project's structure, select "Add," and then choose "Controller." From the available options, select "MVC Controller - Empty". Write the following code in QrCodeController: using Microsoft.AspNetCore.Mvc; using IronBarCode; using System.IO; public class QrCodeController : Controller { private readonly IWebHostEnvironment _environment; public QrCodeController(IWebHostEnvironment environment) { _environment = environment; } public IActionResult CreateQRCode() { return View(); } [HttpPost] public IActionResult CreateQRCode(QRCodeModel generateQRCode) { try { // Creating QR Code GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText); string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filePath = Path.Combine(path, "qrcode.png"); barcode.SaveAsPng(filePath); string fileName = Path.GetFileName(filePath); string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}"; ViewBag.QrCodeUri = imageUrl; } catch (Exception ex) { // Handle exceptions // Log the exception details here for troubleshooting and debugging. throw; } return View(); } } using Microsoft.AspNetCore.Mvc; using IronBarCode; using System.IO; public class QrCodeController : Controller { private readonly IWebHostEnvironment _environment; public QrCodeController(IWebHostEnvironment environment) { _environment = environment; } public IActionResult CreateQRCode() { return View(); } [HttpPost] public IActionResult CreateQRCode(QRCodeModel generateQRCode) { try { // Creating QR Code GeneratedBarcode barcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText); string path = Path.Combine(_environment.WebRootPath, "GeneratedQRCode"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string filePath = Path.Combine(path, "qrcode.png"); barcode.SaveAsPng(filePath); string fileName = Path.GetFileName(filePath); string imageUrl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}/GeneratedQRCode/{fileName}"; ViewBag.QrCodeUri = imageUrl; } catch (Exception ex) { // Handle exceptions // Log the exception details here for troubleshooting and debugging. throw; } return View(); } } Imports Microsoft.AspNetCore.Mvc Imports IronBarCode Imports System.IO Public Class QrCodeController Inherits Controller Private ReadOnly _environment As IWebHostEnvironment Public Sub New(ByVal environment As IWebHostEnvironment) _environment = environment End Sub Public Function CreateQRCode() As IActionResult Return View() End Function <HttpPost> Public Function CreateQRCode(ByVal generateQRCode As QRCodeModel) As IActionResult Try ' Creating QR Code Dim barcode As GeneratedBarcode = QRCodeWriter.CreateQrCode(generateQRCode.QRCodeText) 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(path, "qrcode.png") barcode.SaveAsPng(filePath) Dim fileName As String = System.IO.Path.GetFileName(filePath) Dim imageUrl As String = $"{Me.Request.Scheme}://{Me.Request.Host}{Me.Request.PathBase}/GeneratedQRCode/{fileName}" ViewBag.QrCodeUri = imageUrl Catch ex As Exception ' Handle exceptions ' Log the exception details here for troubleshooting and debugging. Throw End Try Return View() End Function End Class $vbLabelText $csharpLabel This code sets up a controller that can generate QR codes. When the CreateQRCode action is called, it takes the text for the QR code, generates the QR code image, saves it, and provides the URL for the image in the view for display. More detail is as follows: The controller has a constructor that takes an IWebHostEnvironment parameter to access the web hosting environment. The CreateQRCode action returns a view. The CreateQRCode action with the [HttpPost] attribute takes a QRCodeModel parameter, which contains the QR code text. Inside the action, a QR code is generated using the QRCodeWriter class from the Iron Barcode library. The generated QR code is saved as a PNG image file in a folder called GeneratedQRCode in the web root path. If the GeneratedQRCode folder doesn't exist, it is created. The file path and URL for the saved QR code image are generated. The URL of the QR code image is stored in the ViewBag.QrCodeUri property to be used in the view. Any exceptions that occur during the process are caught and logged. Add CreateQRCode View Now, to add a new view, right-click on the CreateQRCode action method in the QrCodeController class. Select "Add View," then select "Razor View," and click on the "Add" button. A new window will appear as shown below. Write the view name, select template "Create," and select our newly created model class QRCodeModel. Click on Add Button. The view will be created. Replace your view with the below code. @model QRCodeModel @{ ViewData["Title"] = "CreateQRCode"; } <h1>Create QRCode in ASP.NET MVC</h1> <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> <input asp-for="QRCodeText" class="form-control" /> <span asp-validation-for="QRCodeText" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> <div class="form-group"> @if (ViewBag.QrCodeUri != null) { <img src="@ViewBag.QrCodeUri" class="img-thumbnail" alt="Generated QR Code" /> } </div> </form> </div> </div> @section Scripts { @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); } } Now, let's move to the Program.cs class and change the default Controller Route. app.MapControllerRoute( name: "default", pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}" ); app.MapControllerRoute( name: "default", pattern: "{controller=QrCode}/{action=CreateQRCode}/{id?}" ); app.MapControllerRoute(name:= "default", pattern:= "{controller=QrCode}/{action=CreateQRCode}/{id?}") $vbLabelText $csharpLabel This will change the default route from HomeController to our QrCodeController. Now, compile and run the project. Output Enter text in the text box and click on the create button. A QR code will be created and displayed on the screen as shown below. Now, let's add visual styling to our barcode by adding annotation text, QR Code value, and changing the QR Code color. Add Visual Styling in QR Code Add the following line of code inside the CreateQRCode Action method. barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF"); barcode.AddBarcodeValueTextBelowBarcode(); barcode.ChangeBackgroundColor(System.Drawing.Color.White); barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed); barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF"); barcode.AddBarcodeValueTextBelowBarcode(); barcode.ChangeBackgroundColor(System.Drawing.Color.White); barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed); barcode.AddAnnotationTextAboveBarcode("QR Code Generated by Iron PDF") barcode.AddBarcodeValueTextBelowBarcode() barcode.ChangeBackgroundColor(System.Drawing.Color.White) barcode.ChangeBarCodeColor(System.Drawing.Color.MediumVioletRed) $vbLabelText $csharpLabel Now, run the project and generate the QR Code. Conclusion In ASP.NET MVC, integrating IronBarcode is straightforward. It provides a user-friendly interface, making it easy to work with QR codes. By leveraging IronBarcode, you can enhance your application by adding QR code functionality, enabling users to share and access information conveniently. IronBarcode is a valuable library that simplifies the process of generating QR codes and reading QR codes in ASP.NET MVC. It empowers developers to create dynamic applications that utilize the power of QR codes for efficient data sharing and retrieval. Iron Barcode is free for personal use. However, for commercial purposes, you need to buy its commercial license, which comes with a free trial. You may also get a significant discount if you get the complete Iron Suite. Iron Suite is a comprehensive collection of .NET software components designed to simplify development tasks and enhance functionality. It offers five powerful libraries, including Iron Barcode, IronOCR, IronPDF, IronXL, and Iron Webscraper that enable developers to work with barcodes, optical character recognition, PDF processing, Excel, and CSV files seamlessly. You will get all five products for the price of two if you opt to purchase the complete Iron Suite. 常见问题解答 如何在ASP.NET MVC中创建二维码? 您可以通过在Visual Studio中设置项目、使用NuGet命令Install-Package IronBarCode安装IronBarcode库,并在控制器中使用IronBarcode的类生成二维码然后在视图中显示它。 我可以在应用程序中自定义二维码的外观吗? 是的,IronBarcode允许您通过调整大小、分辨率、颜色以及添加徽标或注释来自定义二维码,从而提升二维码的视觉吸引力和功能性。 如何在ASP.NET MVC视图中显示二维码? 在使用IronBarcode生成二维码后,可以通过将图像URL存储在ViewBag中,并在Razor视图中使用HTML <img>标签渲染二维码图像来显示它。 如何在.NET应用程序中解码二维码? 您可以使用IronBarcode在.NET应用程序中解码二维码,该库提供用于扫描和提取多种条码格式(包括二维码)数据的功能,适用于库存管理和票证验证等应用。 IronBarcode库有免费版本吗? IronBarcode对个人使用是免费的,允许开发者试验和测试它的功能。对于商业用途,需要购买许可证,并附有免费试用以进行评估。 在ASP.NET MVC项目中二维码的应用有哪些? 在ASP.NET MVC项目中,二维码可用于快速访问网站、无接触支付、票务、库存管理和移动应用集成,通过提升用户互动和信息传播来增强项目功能。 如何设置ASP.NET MVC项目以生成二维码? 若要设置ASP.NET MVC项目以生成二维码,请使用Visual Studio创建一个包含'模型-视图-控制器'模板的新ASP.NET Core网络应用程序,然后安装IronBarcode库开始在应用程序中生成二维码。 Iron Suite包含哪些库? Iron Suite包含各种.NET库,如Iron Barcode、Iron OCR、Iron PDF、Iron XL和Iron Webscraper,每个库提供特定任务的专门功能,如条码生成、光学字符识别、PDF操作、Excel处理和网页抓取。 Jordi Bardia 立即与工程团队聊天 软件工程师 Jordi 最擅长 Python、C# 和 C++,当他不在 Iron Software 利用这些技能时,他就在游戏编程。分享产品测试、产品开发和研究的责任,Jordi 在持续的产品改进中增加了巨大的价值。多样的经验使他面临挑战并保持投入,他表示这是在 Iron Software 工作的最喜欢的方面之一。Jordi 在佛罗里达州迈阿密长大,并在佛罗里达大学学习计算机科学和统计学。 相关文章 已发布十月 19, 2025 How to Print Barcodes in Crystal Reports with VB.NET Generate and print barcodes in Crystal Reports using VB.NET. Step-by-step tutorial with IronBarcode SDK for reliable barcode integration. 阅读更多 已发布九月 29, 2025 IronBarcode vs. Open-Source Barcode Readers in .NET Learn how to read barcodes in C# using IronBarcode 阅读更多 已发布九月 29, 2025 How to Scan Barcodes in an ASP.NET Application Learn how to Scan Barcodes in ASP.NET using IronBarcode 阅读更多 How to Generate Barcode in VB.NETHow to Generate QR Code in Blazor
已发布十月 19, 2025 How to Print Barcodes in Crystal Reports with VB.NET Generate and print barcodes in Crystal Reports using VB.NET. Step-by-step tutorial with IronBarcode SDK for reliable barcode integration. 阅读更多
已发布九月 29, 2025 IronBarcode vs. Open-Source Barcode Readers in .NET Learn how to read barcodes in C# using IronBarcode 阅读更多
已发布九月 29, 2025 How to Scan Barcodes in an ASP.NET Application Learn how to Scan Barcodes in ASP.NET using IronBarcode 阅读更多