Cómo implementar fácilmente QRCoder en ASP.NET Core usando C #

QRCoder es una biblioteca de implementación de códigos QR muy popular escrita en C #. Está disponible en GitHub . Aquí voy a implementar la biblioteca QRCoder para generar códigos QR en mi aplicación ASP.NET Core. También usaré C #.

Implementaré QRCoder de 3 formas, que son:

1. Cree una imagen de mapa de bits de código QR para cualquier texto.

2. Cree un archivo de código QR (.qrr) para cualquier texto y luego guarde estos archivos en la aplicación.

3. Lea y muestre todos los archivos de código QR (.qrr).

Comencemos con la instalación de QRCoder en ASP.NET Core Framework.

Puede descargar el código completo desde mi repositorio de GitHub .

Instalación

Instale QRCoder a través del Administrador de paquetes NuGet. Si desea utilizar NuGet, simplemente busque "QRCoder" o ejecute el siguiente comando en la consola del Administrador de paquetes de NuGet:

PM> Install-Package QRCoder

El QRCoder se instalará en 1 minuto y estará listo para usar.

Ahora comencemos con la implementación de QRCoder de las 3 formas mencionadas anteriormente.

Cree una imagen de mapa de bits de código QR para cualquier texto

Cree un nuevo controlador llamado ' QRCoderController' dentro de la carpeta Controladores. Se creará el controlador y tendrá solo un Método de acción llamado ' Index' en él:

public IActionResult Index() { return View(); }

Importe los siguientes espacios de nombres en el controlador:

using System; using System.Collections.Generic; using System.Drawing; using System.IO; using Microsoft.AspNetCore.Mvc; using QRCoder;

A continuación, agregue la Acción de índice de tipo [HttpPost]al controlador:

[HttpPost] public IActionResult Index(string qrText) { QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(20); return View(BitmapToBytes(qrCodeImage)); }
Esta acción de índice recibe un parámetro de cadena llamado 'qrText'. Contiene el texto proporcionado por un control de entrada definido en la Vista. Este texto se convertirá en una imagen de mapa de bits de código QR. Las siguientes líneas de código hacen este trabajo:
QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(20);

El objeto QRCode (' qrCode') definido llama a una función estática llamada ' BitmapToBytes()'. El papel de esta función es convertir la imagen de mapa de bits a ' Byte[]'.

Agregue esta función a su controlador:

private static Byte[] BitmapToBytes(Bitmap img) { using (MemoryStream stream = new MemoryStream()) { img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); return stream.ToArray(); } }

Finalmente cree la Vista de índice dentro de la Views/QRCodercarpeta ' ' con el siguiente código:

@model Byte[] @{ Layout = null; }     Implementing QRCoder in ASP.NET Core - Create QR Code  body { background: #111 no-repeat; background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111)); } h1, h2, h3 { text-align: center; color: #FFF; margin: 5px 0; } h1 { font-size: 30px; } h2 a { font-size: 25px; color: #0184e3; text-decoration: none; } h3 { font-size: 23px; border-bottom: solid 3px #CCC; padding-bottom: 10px; } h3 a { color: #00e8ff; text-decoration: none; } h3 a:hover, h2 a:hover { text-decoration: underline; } .container { width: 800px; margin: auto; color: #FFF; font-size: 25px; } .container #content { border: dashed 2px #CCC; padding: 10px; } #reset { padding: 5px 10px; background: #4CAF50; border: none; color: #FFF; cursor: pointer; } #reset:hover { color: #4CAF50; background: #FFF; } #viewContent table { width: 100%; } #viewContent table tr { height: 80px; background: darkcyan; } #viewContent table tr td { width: 50%; padding-left: 5px; } 

Implementing QRCoder in ASP.NET Core - Create QR Code

Read the tutorial on YogiHosting » Reset »

@using (Html.BeginForm(null, null, FormMethod.Post)) {
Enter text for creating QR Code
Submit
} @{ if (Model != null) {

QR Code Successfully Generated

} }

La vista de índice tiene un inputcontrol ' '. El usuario ingresa su texto en este control para crear el Código QR:

/>

Once the QR Code is generated by the Index Action method, its ‘byte’ array is returned to the View as model and then the bitmap image is displayed by the below code:

@{ if (Model != null) { 

QR Code Successfully Generated

} }

Testing the Code

Run your application and go to the URL — ‘//localhost:50755/QRCoder’ to invoke the Index Action method.

In the text box, add your text and click the submit button to create the QR Code Bitmap image.

See this image which illustrates it working:

Create QR Code File (.qrr) for any text and then save these files in the application

You can also generate QR Code files for a text and save it in your website. These files have .qrr extension.

To your controller add the following Action methods called ‘GenerateFile’:

public IActionResult GenerateFile() { return View(); } [HttpPost] public IActionResult GenerateFile(string qrText) { QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q); string fileGuid = Guid.NewGuid().ToString().Substring(0, 4); qrCodeData.SaveRawData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed); QRCodeData qrCodeData1 = new QRCodeData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed); QRCode qrCode = new QRCode(qrCodeData1); Bitmap qrCodeImage = qrCode.GetGraphic(20); return View(BitmapToBytes(qrCodeImage)); }

The [HttpPost] version of this action method generates the QR Code files inside the ‘wwwroot/qrr’ folder. The code that does this work is the following:

QRCodeGenerator qrGenerator = new QRCodeGenerator(); QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrText, QRCodeGenerator.ECCLevel.Q); string fileGuid = Guid.NewGuid().ToString().Substring(0, 4); qrCodeData.SaveRawData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);

Once the .qrr file is created then I am simply reading it for its saved location in the website. Then I am converting it to Bitmap type and finally sending the image’s bytes to the view. The corresponding code is:

QRCodeData qrCodeData1 = new QRCodeData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed); QRCode qrCode = new QRCode(qrCodeData1); Bitmap qrCodeImage = qrCode.GetGraphic(20); return View(BitmapToBytes(qrCodeImage));

Next, add the GenerateFile view inside the ‘Views/QRCoder’ folder and add the following code to it:

@model Byte[] @{ Layout = null; }     Implementing QRCoder in ASP.NET Core - Create QR Code File  body { background: #111 no-repeat; background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111)); } h1, h2, h3 { text-align: center; color: #FFF; margin: 5px 0; } h1 { font-size: 30px; } h2 a { font-size: 25px; color: #0184e3; text-decoration: none; } h3 { font-size: 23px; border-bottom: solid 3px #CCC; padding-bottom: 10px; } h3 a { color: #00e8ff; text-decoration: none; } h3 a:hover, h2 a:hover { text-decoration: underline; } .container { width: 800px; margin: auto; color: #FFF; font-size: 25px; } .container #content { border: dashed 2px #CCC; padding: 10px; } #reset { padding: 5px 10px; background: #4CAF50; border: none; color: #FFF; cursor: pointer; } #reset:hover { color: #4CAF50; background: #FFF; } #viewContent table { width: 100%; } #viewContent table tr { height: 80px; background: darkcyan; } #viewContent table tr td { width: 50%; padding-left: 5px; } 

Implementing QRCoder in ASP.NET Core - Create QR Code File

Read the tutorial on YogiHosting » Reset »

@using (Html.BeginForm(null, null, FormMethod.Post)) {
Enter text for creating QR File
Submit
} @{ if (Model != null) {

QR Code file Successfully Generated

} }

The code of this View is exactly similar to the ‘Index’ View and works exactly like it.

The URL to invoke this View is ‘//localhost:50755/QRCoder/GenerateFile’.

Read and display all the QR Code Files (.qrr)

You can also read all the .qrr files saved in the website. Go to your controller and add a new action called ‘ViewFile’:

public IActionResult ViewFile() { List
     
       fileData=new List
      
       (); KeyValuePair data; string[] files = Directory.GetFiles("wwwroot/qrr"); foreach (string file in files) { QRCodeData qrCodeData = new QRCodeData(file, QRCodeData.Compression.Uncompressed); QRCode qrCode = new QRCode(qrCodeData); Bitmap qrCodeImage = qrCode.GetGraphic(20); Byte[] byteData = BitmapToBytes(qrCodeImage); data = new KeyValuePair(Path.GetFileName(file), byteData); fileData.Add(data); } return View(fileData); }
      
     

In this action method, I read the filed located in the ‘qrr’ folder using the code:

Directory.GetFiles("wwwroot/qrr")

Then I add each qrr file’s bytes and name inside a List object.

This object is returned to the View at the end:

return View(fileData);

Finally create the ‘ViewFile’ View inside the ‘Views/QRCoder’ folder with the following code:

@model List 
     
       @{ Layout = null; } Implementing QRCoder in ASP.NET Core - View QR Code Files body { background: #111 no-repeat; background-image: -webkit-gradient(radial, 50% 0, 150, 50% 0, 300, from(#444), to(#111)); } h1, h2, h3 { text-align: center; color: #FFF; margin: 5px 0; } h1 { font-size: 30px; } h2 a { font-size: 25px; color: #0184e3; text-decoration: none; } h3 { font-size: 23px; border-bottom: solid 3px #CCC; padding-bottom: 10px; } h3 a { color: #00e8ff; text-decoration: none; } h3 a:hover, h2 a:hover { text-decoration: underline; } .container { width: 800px; margin: auto; color: #FFF; font-size: 25px; } .container #content { border: dashed 2px #CCC; padding: 10px; } #reset { padding: 5px 10px; background: #4CAF50; border: none; color: #FFF; cursor: pointer; } #reset:hover { color: #4CAF50; background: #FFF; } #viewContent table { width: 100%; } #viewContent table tr { height: 80px; background: darkcyan; } #viewContent table tr td { width: 50%; padding-left: 5px; } #viewContent table tr td img { width: 150px; } #viewContent table tr td span { display: block; } 
      

Implementing QRCoder in ASP.NET Core - View QR Code Files

Read the tutorial on YogiHosting » Reset »

@foreach (KeyValuePair k in Model) { }
@k.Key

This View displays all the qrr files as bitmap images inside a ‘HTML’ table. The below code creates the HTML table:


     
        @foreach (KeyValuePair k in Model) { 
        } 
      
@k.Key

Testing the Code

Run your application and go to the URL — ‘//localhost:50755/QRCoder/ViewFile’ to invoke the ViewFile Action method. You will see all the .qrr files saved in your website.

See the below image which illustrates it working:

You can download the full code from my GitHub Respositiory.

Conclusion

I hope you love this repository which will help you to use QRCoder in your ASP.NET Core Project. Make sure you like this repository to show your love to it.

If you need any help in ASP.NET Core then let me know in the below comments section.

I publish 2 web development articles per week. Consider following me and get email notification whenever I publish a new tutorial on Medium. If this post was helpful, please click the clap button for a few times to show your support! It will bring a smile on my face and motivate me to write more for the readers like you.

I have also published another tutorial on freeCodeCamp, if you would like to see it too — How to create a login feature with Bootstrap Modal and jQuery AJAX

Thanks and Happy Coding!