ASP.NET Web API and Machine Learning

Developers can now expose intelligent models through ASP.NET Web API. This article provides a step-by-step guide on how to incorporate a machine learning model into an ASP.NET Web API application.
Environment Set Up
• .NET 6 SDK
• Visual Studio 2022
Open Visual Studio
Create a new project of type ASP.NET Core Web API
Provide Project Name as “MLWithAPI”
Click Create
Development Steps
Install below ML.NET packages
Install-Package Microsoft.ML
Install-Package Microsoft.ML.Data
Add a folder named Models. Create the following classes:
namespace MLWithAPI.Models
{
public class SentimentInput
{
public string Text { get; set; }
}
public class SentimentOutput
{
public string Sentiment { get; set; }
public float Confidence { get; set; }
}
}
Add a Services folder and create a class MLModelService:
using
Microsoft.ML
;
using MLWithAPI.Models;
namespace
MLWithAPI.Services
{
public class MLModelService
{
private readonly MLContext mlContext;
private readonly ITransformer model;
public MLModelService()
{
mlContext = new MLContext();
model = mlContext.Model.Load("MLModels/sentiment
model.zip
", out _);
}
public SentimentOutput Predict(SentimentInput input)
{
var predictionEngine = mlContext.Model.CreatePredictionEngine<SentimentInput,SentimentPrediction>(model);
var prediction = predictionEngine.Predict(input);
return new SentimentOutput
{
Sentiment = prediction.PredictedLabel,
Confidence = prediction.Score.Max()
};
}
}
public class SentimentPrediction
{
public string PredictedLabel { get; set; }
public float[] Score { get; set; }
}
}
In Program.cs, register the MLModelService:
builder.Services.AddSingleton();
Add a Controllers folder and create MySentimentController:
using Microsoft.AspNetCore.Mvc;
using MLWithAPI.Models;
using
MLWithAPI.Services
;
[ApiController]
[Route("api/[controller]")]
public class MySentimentController : ControllerBase
{
private readonly MLModelService _mlService;
public MySentimentController(MLModelService mlService) { _mlService = mlService; }
[HttpPost("analyze")]
public IActionResult AnalyzeSentiment([FromBody] SentimentInput input)
{
var result = _mlService.Predict(input); return Ok(result);
}
}
Start the application. Use Postman to test the endpoint:
POST https://localhost:5001/api/sentiment/analyze
Content-Type: application/json
{
"text": "I like this place"
}
Response:
{
"sentiment": "Positive",
"confidence": 0.95
}
Conclusion
Intelligent applications can be realized through the integration of ASP.NET Web API with machine learning. Whether utilizing cloud-based AI services or pre-trained models with ML.NET, this method makes intelligent, scalable, and reliable solutions possible.
Further Learning Resources
Subscribe to my newsletter
Read articles from Ujwal Watgule directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
