How to Set up a Simple Barcode Reading Server in ASP.NET Core

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. It is convenient to use it to build web APIs and web apps. In this article, we are going to talk about how to set up a simple barcode reading server in ASP.NET Core with Dynamsoft Barcode Reader.

New Project

Create a new ASP.NET Core Empty project named BarcodeReader using dotnet:

dotnet new web -n BarcodeReader

The template uses the minimal API design since .NET 6.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Add Dependencies

Install Dynamsoft Barcode Reader from nuget.

dotnet add package Dynamsoft.DotNet.Barcode --version 9.6.20

Add a Barcode Reading Endpoint

Next, let’s make add a barcode reading endpoint for reading barcodes from images.

Request example:

{
  "base64":"<base64-encoded image>"
}

Response example:

{
  "elapsedTime":20,
  "results": [
    "barcodeText":"example",
    "barcodeFormat":"QR_CODE",
    "x1":0,
    "x2":50,
    "x3":50,
    "x4":0,
    "y1":10,
    "y2":10,
    "y3":50,
    "y4":50
  ]
}
  1. Set the license of Dynamsoft Barcode Reader when the app starts. You can apply for a license here.

    initLicense();
    void initLicense() {
        string errorMsg;
        EnumErrorCode errorCode = BarcodeReader.InitLicense("DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ==", out errorMsg); //one-day trial license
           
        if (errorCode != EnumErrorCode.DBR_SUCCESS)
        {
            // Add your code for license error processing;
            Console.WriteLine(errorMsg);
        }
    }
    
  2. Add an endpoint to handle post requests for reading barcode images.

    app.MapPost("/readBarcodes", (Image image) => {
        BarcodeReader reader = new BarcodeReader();
        long startTime = getUnixTimestamp();
        TextResult[] results = reader.DecodeBase64String(image.base64,"");
        long elapsedTime = getUnixTimestamp() - startTime;
        List<BarcodeResult> barcodeResults = wrappedResults(results);
        DecodingResponse response = new DecodingResponse(
          barcodeResults,elapsedTime
        );
        return response;
    });
       
    long getUnixTimestamp(){
        DateTimeOffset dto = new DateTimeOffset(DateTime.Now);
        return dto.ToUnixTimeMilliseconds();
    }
       
    List<BarcodeResult> wrappedResults(TextResult[] results) {
        List<BarcodeResult> barcodeResults = new List<BarcodeResult>();
        foreach (var result in results)
        {
          BarcodeResult barcodeResult = new BarcodeResult(
            barcodeText: result.BarcodeText,
            barcodeFormat: result.BarcodeFormatString,
            x1: result.LocalizationResult.ResultPoints[0].X,
            x2: result.LocalizationResult.ResultPoints[1].X,
            x3: result.LocalizationResult.ResultPoints[2].X,
            x4: result.LocalizationResult.ResultPoints[3].X,
            y1: result.LocalizationResult.ResultPoints[0].Y,
            y2: result.LocalizationResult.ResultPoints[1].Y,
            y3: result.LocalizationResult.ResultPoints[2].Y,
            y4: result.LocalizationResult.ResultPoints[3].Y
          );
          barcodeResults.Add(barcodeResult);
        }
        return barcodeResults;
    }
    
  3. Three records are used for this endpoint.

    record Image(string base64);
    record DecodingResponse(
      List<BarcodeResult> results,
      long elapsedTime
    );
    record BarcodeResult(
      string barcodeText,
      string barcodeFormat,
      int x1,
      int x2,
      int x3,
      int x4,
      int y1,
      int y2,
      int y3,
      int y4
    );
    

Have a Test

We can then write a web page to test the API using AJAX:

let xhr = new XMLHttpRequest();
let pay_load = {};
let dataURL = img.src;
let base64 = dataURL.substring(dataURL.indexOf(",")+1,dataURL.length);
pay_load["base64"] = base64;

xhr.open('POST', url);
xhr.setRequestHeader('content-type', 'application/json'); 

xhr.onreadystatechange = function(){
  if(xhr.readyState === 4){
    if (xhr.status === 200) {
      console.log(xhr.responseText);
    }
  }
}
xhr.send(JSON.stringify(pay_load));

To serve the web page as static files, we need to add the following code and put the file under wwwroot:

app.UseStaticFiles();

We are not going to cover the page in detail. You can check out the source code in the GitHub repo.

Front-End

Enable Swagger Documentation

We can use Swagger to document the APIs.

  1. Install Swagger.

    dotnet add package Swashbuckle.AspNetCore --version 6.1.4   
    
  2. Add the following code to use it:

    using Microsoft.OpenApi.Models;
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen(c =>
       {
           c.SwaggerDoc("v1", new OpenApiInfo { Title = "Barcode Reading API", Description = "Read barcodes from images", Version = "v1" });
       });
    app.UseSwagger();
    app.UseSwaggerUI(c =>
       {
         c.SwaggerEndpoint("/swagger/v1/swagger.json", "Barcode Reading API V1");
       });
    

Then we can visit the Swagger’s documentation page.

Swagger

Source Code

The source code of the project is available here: https://github.com/tony-xlh/Barcode-Reading-Server-ASP-NET-Core/

References

Build a web API with minimal API, ASP.NET Core, and .NET