How to Generate & Create QR Code in ASP.NET C# (Full Example)

How to Generate & Create QR Code in ASP.NET C# (Full Example)

2025-08-08 05:38:37 Written by  zaki zou
Rate this item
(0 votes)

Generate QR Code in ASP.NET C# using Spire.Barcode for .NET – Tutorial Overview

QR codes have become a standard feature in modern web applications, widely used for user authentication, contactless transactions, and sharing data like URLs or contact information. For developers working with ASP.NET, implementing QR code generation using C# is a practical requirement in many real-world scenarios.

In this article, you’ll learn how to generate QR codes in ASP.NET using Spire.Barcode for .NET. We’ll walk through a complete example based on an ASP.NET Core Web App (Razor Pages) project, including backend logic and a simple UI to display the generated code. The same approach can be easily adapted to MVC, Web API, and Web Forms applications.

Article Overview


1. Project Setup and Dependencies

Prerequisites

To follow along, make sure you have:

  • Visual Studio 2019 or newer
  • .NET 6 or later
  • ASP.NET Core Web App (Razor Pages Template)
  • NuGet package: Spire.Barcode for .NET

Install Spire.Barcode for .NET

Install the required library using NuGet Package Manager Console:

Install-Package Spire.Barcode

Spire.Barcode is a fully self-contained .NET barcode library that supports in-memory generation of QR codes without external APIs. You can also use Free Spire.Barcode for .NET for smaller projects.


2. Generate QR Code in ASP.NET Using C#

This section describes how to implement QR code generation in an ASP.NET Core Web App (Razor Pages) project. The example includes a backend C# handler that generates the QR code using Spire.Barcode for .NET, and a simple Razor Page frontend for user input and real-time display.

Step 1: Add QR Code Generation Logic in PageModel

The backend logic resides in the Index.cshtml.cs file. It processes the form input, generates a QR code using Spire.Barcode, and returns the result as a Base64-encoded image string that can be directly embedded in HTML.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Barcode;

public class IndexModel : PageModel
{
    [BindProperty]
    public string InputData { get; set; }

    public string QrCodeBase64 { get; set; }

    public void OnPost()
    {
        if (!string.IsNullOrWhiteSpace(InputData))
        {
            QrCodeBase64 = GenerateQrCodeBase64(InputData);
        }
    }
    
    private string GenerateQrCodeBase64(string input)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,            // QR code type
            Data = input,                         // Main encoded data
            Data2D = input,                       // Required for 2D barcode, usually same as Data
            QRCodeDataMode = QRCodeDataMode.Byte, // Byte mode (supports multilingual content)
            QRCodeECL = QRCodeECL.M,              // Medium error correction (15%)
            X = 3,                                // Module size (affects image dimensions)
            ShowText = false,                     // Hide default barcode text
            ShowBottomText = true,                // Show custom bottom text
            BottomText = input                    // Bottom text to display under the QR code
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        var qrImage = generator.GenerateImage();
        qrImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return Convert.ToBase64String(ms.ToArray());
    }
}

Key Components:

  • BarcodeSettings: Specifies the QR code's core configuration, such as type (QRCode), data content, encoding mode, and error correction level.

  • BarCodeGenerator: Takes the settings and generates the QR code image as a System.Drawing.Image object using the GenerateImage() method.

  • Base64 Conversion: Converts the image to a Base64 string so it can be directly embedded into the HTML page without saving to disk.

This approach keeps the entire process in memory, making it fast, portable, and suitable for serverless or cloud-hosted applications.

Step 2: Create the Razor Page for User Input and QR Code Display and Download

The following Razor markup in the Index.cshtml file defines a form for entering text or URLs, displays the generated QR code upon submission, and provides a button to download the QR code image.

@page
@model IndexModel
@{
    ViewData["Title"] = "QR Code Generator";
}

<h2>QR Code Generator</h2>

<form method="post">
    <label for="InputData">Enter text or URL:</label>
    <input type="text" id="InputData" name="InputData" style="width:300px;" required />
    <button type="submit">Generate QR Code</button>
</form>

@if (!string.IsNullOrEmpty(Model.QrCodeBase64))
{
    <div style="margin-top:20px">
        <img src="data:image/png;base64,@Model.QrCodeBase64" alt="QR Code" />
        <br />
        <a href="data:image/png;base64,@Model.QrCodeBase64" download="qrcode.png">Download QR Code</a>
    </div>
}

The Base64-encoded image is displayed directly in the browser using a data: URI. This eliminates the need for file storage and allows for immediate rendering and download.

The following screenshot shows the result after submitting text input.

Generated QR Code displayed on Razor Page in ASP.NET Core

If you need to scan QR codes instead, please refer to How to Scan QR Codes in C#.


3. Customize QR Code Output

Spire.Barcode provides several customization options through the BarcodeSettings class to control the appearance and behavior of the generated QR code:

Property Function Example
QRCodeDataMode Text encoding mode QRCodeDataMode.Byte
QRCodeECL Error correction level QRCodeECL.H (high redundancy)
X Module size (resolution) settings.X = 6
ImageWidth/Height Control dimensions of QR image settings.ImageWidth = 300
ForeColor Set QR code color settings.ForeColor = Color.Blue
ShowText Show or hide text below barcode settings.ShowText = false
BottomText Custom text to display below barcode settings.BottomText = "Scan Me"
ShowBottomText Show or hide the custom bottom text settings.ShowBottomText = true
QRCodeLogoImage Add a logo image to overlay at QR code center settings.QRCodeLogoImage = System.Drawing.Image.FromFile("logo.png");

These properties help you tailor the appearance of your QR code for branding, readability, or user interaction purposes.

To explore more QR code settings, refer to the BarcodeSettings API reference.


4. Apply Logic in MVC, Web API, and Web Forms

The same QR code generation logic used in Razor Pages can also be reused in other ASP.NET frameworks such as MVC, Web API, and Web Forms.

MVC Controller Action

In an MVC project, you can add a Generate action in a controller (e.g., QrController.cs) to generate and return the QR code image directly:

public class QrController : Controller
{
    public ActionResult Generate(string data)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,
            Data = data,
            QRCodeDataMode = QRCodeDataMode.Byte,
            QRCodeECL = QRCodeECL.M,
            X = 5
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return File(ms.ToArray(), "image/png");
    }
}

This method returns the QR code as a downloadable PNG file, ideal for server-side rendering.

Web API Endpoint

For Web API, you can define a GET endpoint in a controller such as QrApiController.cs that responds with the generated image stream:

[ApiController]
[Route("api/[controller]")]
public class QrApiController : ControllerBase
{
    [HttpGet("generate")]
    public IActionResult GetQr(string data)
    {
        var settings = new BarcodeSettings
        {
            Type = BarCodeType.QRCode,
            Data = data
        };

        var generator = new BarCodeGenerator(settings);
        using var ms = new MemoryStream();
        generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return File(ms.ToArray(), "image/png");
    }
}

This approach is suitable for frontends built with React, Vue, Angular, or any JavaScript framework.

Web Forms Code-Behind

In ASP.NET Web Forms, you can handle QR code generation in the code-behind of a page like Default.aspx.cs:

protected void btnGenerate_Click(object sender, EventArgs e)
{
    var settings = new BarcodeSettings
    {
        Type = BarCodeType.QRCode,
        Data = txtInput.Text
    };

    var generator = new BarCodeGenerator(settings);
    using var ms = new MemoryStream();
    generator.GenerateImage().Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    imgQR.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}

The generated image is embedded directly into an asp:Image control using a Base64 data URI.


5. Conclusion

With Spire.Barcode for .NET, you can seamlessly generate and customize QR codes across all ASP.NET project types — Razor Pages, MVC, Web API, or Web Forms. The solution is fully offline, fast, and requires no third-party API.

Returning images as Base64 strings simplifies deployment and avoids file management. Whether you're building authentication tools, ticketing systems, or contact sharing, this approach is reliable and production-ready.


FAQs

Q: Does Spire.Barcode support Unicode characters like Chinese or Arabic?

A: Yes. Use QRCodeDataMode.Byte for full Unicode support.

Q: Can I adjust QR code size and color?

A: Absolutely. Use properties like X, ForeColor, and ImageWidth.

Q: Is this solution fully offline?

A: Yes. It works without any external API calls or services.

Q: Can I expose this QR logic via API?

A: Yes. Use ASP.NET Web API to serve generated images to client apps.

Additional Info

  • tutorial_title:
Last modified on Friday, 08 August 2025 05:39