AI with ASP.NET Core: Building Intelligent Applications with Machine Learning Models

  • Post category:asp.net core
  • Reading time:5 mins read

Artificial Intelligence (AI) is transforming the way we build applications, enabling developers to add smart features such as predictions, image recognition, and natural language processing to their software. ASP.NET Core, a popular open-source framework for building modern web applications, provides a robust platform to integrate AI and Machine Learning (ML) models, offering a seamless experience for developers. In this article, we will explore how to harness AI with ASP.NET Core by building an intelligent application that utilizes a pre-trained ML model.

Prerequisites

Before we dive into the code, make sure you have the following tools and technologies installed:

– .NET Core SDK (v3.1 or later)
– Visual Studio or Visual Studio Code
– ML.NET (a free, cross-platform, and open-source machine learning framework for .NET)
– Basic knowledge of C# and ASP.NET Core

 Step 1: Setting Up the ASP.NET Core Project

1. Create a New ASP.NET Core Web API Project:

Open your terminal or command prompt and run the following commands to create a new ASP.NET Core Web API project:

dotnet new webapi -n AIwithAspNetCore
cd AIwithAspNetCore

2. Install ML.NET NuGet Packages:

ML.NET is the machine learning framework that we’ll use to integrate AI capabilities into our ASP.NET Core application. Install the necessary NuGet packages using the following command:

dotnet add package Microsoft.ML
dotnet add package Microsoft.ML.ImageAnalytics

Step 2: Building an Image Classification API with ML.NET

In this example, we’ll create an API that can classify images using a pre-trained ML model. We’ll use the `ResNet50` model, which is a popular deep learning model trained to recognize a wide variety of images.

1. Create the Input Model:

In the `Models` folder, create a new class called `ImageData.cs` to represent the input data:

namespace AIwithAspNetCore.Models
{
   public class ImageData
   {
      public byte[] ImageBytes { get; set; }
   }
}

2. Load the Pre-Trained Model:

Next, create a new class called `ImageClassifier.cs` in the `Services` folder. This class will load the pre-trained ResNet50 model and perform image classification.

using Microsoft.ML;
using Microsoft.ML.Data;
using System.Linq;

namespace AIwithAspNetCore.Services {
public class ImageClassifier {
private readonly MLContext _mlContext;
private readonly PredictionEngine < ImageData, ImagePrediction > _predictionEngine;

public ImageClassifier() {
_mlContext = new MLContext();
var model = LoadModel("resnet50_model.zip");
_predictionEngine = _mlContext.Model.CreatePredictionEngine < ImageData, ImagePrediction > (model);
}

private ITransformer LoadModel(string modelPath) {
return _mlContext.Model.Load(modelPath, out
var modelInputSchema);
}

public string ClassifyImage(ImageData imageData) {
var prediction = _predictionEngine.Predict(imageData);
return prediction.PredictedLabel;
}
}

public class ImagePrediction {
       [ColumnName("PredictedLabel")]
       public string PredictedLabel {get;set;}
     }
}

3. Create the API Controller:

Now, create a new API controller called `ImageClassificationController.cs` in the `Controllers` folder. This controller will expose an endpoint that accepts an image and returns the classification result.

using AIwithAspNetCore.Models;
using AIwithAspNetCore.Services;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace AIwithAspNetCore.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ImageClassificationController : ControllerBase
{
private readonly ImageClassifier _imageClassifier;

public ImageClassificationController(ImageClassifier imageClassifier)
{
_imageClassifier = imageClassifier;
}

[HttpPost("classify")]
public ActionResult<string> Classify([FromForm] IFormFile imageFile)
{
  using var memoryStream = new MemoryStream();
  imageFile.CopyTo(memoryStream);

  var imageData = new ImageData
 {
    ImageBytes = memoryStream.ToArray()
 };

   var result = _imageClassifier.ClassifyImage(imageData);
 
   return Ok(result);
   }
  }
}

4. Register the Services in Startup.cs:

Finally, register the `ImageClassifier` service in the `Startup.cs` file so that it can be injected into the controller.

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllers();
  services.AddSingleton<ImageClassifier>();
}

Step 3: Running and Testing the API

1. Run the Application:

Use the following command to run the application:

dotnet run

2. Test the API:

You can test the API using tools like Postman or curl. Send a `POST` request to the `/api/imageclassification/classify` endpoint with an image file, and you’ll receive the classification result in the response.

Example using `curl`:

curl -X POST "https://localhost:5001/api/imageclassification/classify" -F "imageFile=@path_to_your_image.jpg"

Conclusion

In this article, we’ve walked through the process of integrating a pre-trained ML model into an ASP.NET Core application to build an intelligent image classification API. This approach can be extended to other AI and ML use cases, such as natural language processing, recommendation systems, and predictive analytics.

As AI continues to evolve, integrating machine learning models into web applications will become increasingly common. With tools like ML.NET, ASP.NET Core developers can easily harness the power of AI to create smarter, more capable applications.

check this :

Boosting ASP.NET Core Application Performance with Caching

Leave a Reply