Create an API for generating QR codes using ASP.NET Core

  之前同仁反應使用 Google 的 QR Code API 有時會無法使用,查了相關資訊後,有了想透過撰寫這個 API 來學習 C# 的想法,花了些時間摸索,還真被我搞出來。此 API 的功能為在網址輸入值,便可直接在瀏覽器產生 QRCode 的圖片,以下會以第一次撰寫 ASP.NET Core / C# 的新手角度來說明。

新增專案
「檔案 → 新增 → 專案」上面的篩選類別選擇「C#, Windows, WebAPI」
選擇 ASP.NET Core Web API

輸入一個專案名稱

這邊我有勾選「使用控制器」感覺程式稍微分類一下比較清楚
「啟用 OpenAPI 支援」則是取消勾選因為用不到

安裝 QRCoder 套件
「專案 → 管理 NuGet 套件」

搜尋 “QRCoder”,並安裝。

新增 Controller
在 [Controllers] 目錄按右鍵,選擇「加入 → 控制器」。

選擇 「API」項目中的「API 控制器 – 空白」。

再次選擇「API 控制器 – 空白」。

Write the program
Write the program in the newly added Controller:

// using Microsoft.AspNetCore.Http;
// 系統產生,沒用到。

using Microsoft.AspNetCore.Mvc;
using QRCoder;

namespace QRCode.Controllers
{
    [Route("[controller]")]
    // 指定路徑為 xxx.com/QRCodeGen,
    // 不指定時,會是 xxx.com/。

    // [ApiController]
    // 系統產生,沒用到。

    public class QRCodeGenController : ControllerBase
    {
        [HttpGet]
        [Route("{qrText}")]
        public IActionResult GetQrCode(string qrText)
        {
            byte[] image = PngByteQRCodeHelper.GetQRCode(qrText, QRCodeGenerator.ECCLevel.Q, 10);
            return File(image, "image/png");
        }
    }
}

Test results
Select 'Debug → Start Debugging'。

Enter the Controller name and the value to generate the QR code at the end of the URL,Press Enter to generate the QR code image。

Additional notes
This program was written six months ago,I remember encountering several issues and gradually installed the following packages,For reference:
ASP.NET Core runtime 6.0.36

  • x64 (Development side): aspnetcore-runtime-6.0.28-win-x64.exe
  • Hosting Bundle (IIS side): dotnet-hosting-6.0.28-win.exe

<Reference Link>

1 Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.