通过ASP.NET Core制作一个QRCode生成器的API

之前同事反映使用Google的QRCode 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 控制器空白」

撰寫程式
在剛剛新增的 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");
        }
    }
}

測試結果
Select 'Debug → Start Debugging'。

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

Additional notes
This program was written six months ago,I remember encountering a few 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 条留言

留下回复

您的电子邮件地址不会被公开. 必填项已标注 *

本网站使用 Akismet 来减少垃圾评论. 了解您的评论数据如何被处理.