Previously, colleagues reported that Google’s QR Code API sometimes failed to work.,After checking the relevant information,Got the idea to learn C# by writing this API,Spent some time exploring,I really got it out of you。The function of this API is to enter a value in the URL,You can generate QRCode images directly in the browser,The following will be written for the first time ASP.NET Core / Explained from the perspective of a newbie in C#。
Add new project
"File → Add → Project",Select "C#" for the filter category above, Windows, WebAPI」,
select ASP.NET Core Web API。
Enter a project name。
Here I have checked "Use Controller",I feel like it would be clearer if the program is classified a little bit.。
"Enable OpenAPI support" is unchecked,Because there is no need。
Install QRCoder package
"Project → Manage NuGet Packages"。
Search “QRCoder”,And install。
Add Controller
In [Controllers] Right click on the directory,Select "Join → Controller"。
Select "API Controller" in the "API" project – blank"。
Select API Controller again – blank"。
Write a program
Write a 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 name of the Controller and the value to generate QRCode at the end of the address bar,Press Enter to generate a QRCode image。
Other supplements
This program was written half a year ago,I have the impression that I encountered several situations and installed the following packages one after another.,for reference:
ASP.NET Core execution phase 6.0.36
- x64 (Development side): aspnetcore-runtime-6.0.28-win-x64.exe
- Hosting Bundle (IIS edge): dotnet-hosting-6.0.28-win.exe
"Reference Link"
[…] QRCode 產生器的 API 後,摸不著頭緒要怎麼把程式變成 IIS […]