Stories

Detail Return Return

在 ASP.NET Core Razor Page 中用 C# 生成二維碼 - Stories Detail

二維碼(QR Code)已廣泛應用於網址分享、支付鏈接、票務驗證、身份登錄等場景。在 ASP.NET Core 項目中,我們可以通過 C# 結合 Free Spire.Barcode for .NET 快速生成二維碼,並將其直接顯示在網頁上,支持在線下載。

本文將以 ASP.NET Core Web App(Razor Page) 為示例,演示如何實現 輸入文本/URL → 生成二維碼 → 在線顯示與下載 的完整流程。

  • 創建輸入與顯示二維碼的頁面
  • 在後台生成二維碼圖片並返回 Base64 編碼
  • 將二維碼顯示到頁面並提供下載功能
本文示例使用 Free Spire.Barcode for .NET 生成二維碼。你可以通過 NuGet 安裝:
dotnet add package FreeSpire.Barcode

1. 創建前端頁面(Index.cshtml)

在 Razor Page 中,我們需要一個輸入框供用户填寫二維碼內容,以及一個提交按鈕觸發後台生成邏輯。生成的二維碼將直接以圖片的形式顯示,並提供下載鏈接。

優化後的 HTML 代碼示例:

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

<h2 style="font-family: Arial; color: #2c3e50;">QR Code Generator</h2>

<form method="post" style="margin-bottom:20px; background-color:#f9f9f9; padding:15px; border-radius:5px; width: fit-content;">
    <label for="InputData" style="font-weight:bold;">Enter text or URL:</label><br />
    <input type="text" id="InputData" name="InputData" style="width:300px; padding:5px; margin:5px 0;" required />
    <button type="submit" style="padding:5px 15px; background-color:#3498db; color:white; border:none; border-radius:3px; cursor:pointer;">
        Generate QR Code
    </button>
</form>

@if (!string.IsNullOrEmpty(Model.QrCodeBase64))
{
    <div style="margin-top:20px; border:1px solid #ddd; padding:10px; display:inline-block; border-radius:5px;">
        <img src="data:image/png;base64,@Model.QrCodeBase64" alt="QR Code" style="display:block; margin-bottom:10px;" />
        <a href="data:image/png;base64,@Model.QrCodeBase64" download="qrcode.png" 
           style="background-color:#2ecc71; color:white; padding:5px 10px; border-radius:3px; text-decoration:none;">
            Download QR Code
        </a>
    </div>
}

前端實現要點:

  1. 表單通過 POST 提交輸入數據;
  2. 二維碼顯示採用 data:image/png;base64 形式,無需保存到磁盤;
  3. 提供下載按鈕,直接保存二維碼圖片到本地。

2. 後端二維碼生成邏輯(Index.cshtml.cs)

後台邏輯的核心是利用 Spire.Barcode 提供的 BarcodeSettingsBarCodeGenerator 類生成二維碼,並將生成的圖片轉換為 Base64 字符串返回給前端頁面顯示。

代碼示例:

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,            // 指定二維碼類型
            Data = input,                         // 編碼數據
            Data2D = input,                       // 二維碼需要設置 Data2D
            QRCodeDataMode = QRCodeDataMode.Byte, // 字節模式(支持多語言)
            QRCodeECL = QRCodeECL.M,              // 中等級糾錯(可恢復 15% 數據)
            X = 3,                                // 模塊大小
            ShowText = false,                     // 不顯示默認條碼文字
            ShowBottomText = true,                // 顯示自定義底部文字
            BottomText = input                    // 底部顯示輸入內容
        };

        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());
    }
}

關鍵技術説明:

  • QRCodeDataMode.Byte:支持中文、日文等多字節字符,避免亂碼;
  • QRCodeECL.M:中等級糾錯,適合大部分場景;
  • BottomText:可自定義底部文字,比如顯示原始輸入內容。

3. 運行效果

當用户在輸入框中填寫內容並點擊“Generate QR Code”按鈕後,頁面會立即生成二維碼並顯示,同時提供“Download QR Code”按鈕,方便保存到本地。

示例效果(假設輸入為 https://www.sample.com/):
ASP.NET 生成二維碼示例


總結

通過 ASP.NET Core Razor Page + Spire.Barcode for .NET,我們可以非常方便地實現網頁端輸入數據並生成二維碼、即時顯示二維碼圖片,並直接提供圖片下載功能。這種方式無需額外的臨時文件存儲,生成速度快,適合在登錄驗證、活動報名、文件分享等場景中使用。


如果你需要更復雜的二維碼功能(如帶 Logo、顏色定製、批量生成等),可以繼續擴展 BarcodeSettings 的參數。更多文檔可參考:Spire.Barcode for .NET 官方教程

user avatar jkdataapi Avatar zhoutk Avatar dotnetcore_5c7f68d071ec6 Avatar
Favorites 3 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.