Introduction

AI (Artificial Intelligence) and ML (Machine Learning) are changing the way web applications interact with users. From recommendations, chatbots, and predictions to image recognition, AI/ML features make applications smarter and more engaging.

In this tutorial, we will explore how to integrate AI/ML into a full-stack app using ASP.NET Core as the backend and Angular as the frontend. We will also discuss options like Azure Cognitive Services , OpenAI API , and custom ML models .

Why Add AI/ML to Your Apps?

Architecture Diagram

  
    +----------------+           HTTP/API           +---------------------+
 |   Angular App  | <-------------------------> | ASP.NET Core Backend |
 |  (Frontend)    |                                | (API & ML Logic)   |
 +----------------+                                +---------------------+
        ^                                                      |
        |                                                      |
        +------------------ AI/ML Services (Azure Cognitive, Custom ML, OpenAI) --------+
  

Explanation

  1. Angular sends input data (text, image, user behavior) to the backend.

  2. ASP.NET Core processes the request and calls AI/ML services or models.

  3. AI/ML service returns predictions, recommendations, or results.

  4. Angular displays results to the user in real-time.

Step 1. Using AI/ML API (Example: Text Sentiment Analysis)

  1. Backend: ASP.NET Core Web API

  
    dotnet add package RestSharp
  
  
    using Microsoft.AspNetCore.Mvc;
using RestSharp;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class AiController : ControllerBase
{
    private readonly string apiKey = "<YOUR_OPENAI_API_KEY>";

    [HttpPost("sentiment")]
    public async Task<IActionResult> AnalyzeSentiment([FromBody] string text)
    {
        var client = new RestClient("https://api.openai.com/v1/completions");
        var request = new RestRequest(Method.POST);
        request.AddHeader("Authorization", $"Bearer {apiKey}");
        request.AddJsonBody(new
        {
            model = "text-rg-003",
            prompt = $"Analyze the sentiment of this text: {text}",
            max_tokens = 60
        });

        var response = await client.ExecuteAsync(request);
        return Ok(response.Content);
    }
}
  

Step 2. Angular Frontend Integration

  1. Create AI Service ( ai.service.ts )

  
    import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AiService {
  private apiUrl = 'https://localhost:5001/api/ai';

  constructor(private http: HttpClient) {}

  analyzeSentiment(text: string): Observable<any> {
    return this.http.post(`${this.apiUrl}/sentiment`, text);
  }
}
  
  1. Consume in app.component.ts

  
    import { Component } from '@angular/core';
import { AiService } from './ai.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  text = '';
  sentimentResult = '';

  constructor(private aiService: AiService) {}

  analyze() {
    this.aiService.analyzeSentiment(this.text).subscribe(result => {
      this.sentimentResult = result;
    });
  }
}
  
  1. Update app.component.html

  
    <div>
  <h2>AI Sentiment Analysis</h2>
  <textarea [(ngModel)]="text" placeholder="Enter text here"></textarea>
  <button (click)="analyze()">Analyze</button>
  <p><b>Result:</b> {{ sentimentResult }}</p>
</div>
  

Step 3. Advanced Features

Step 4. Tips for Full-Stack AI/ML Integration

  1. Always validate user input before sending to the AI/ML API.

  2. Cache AI/ML responses if results are reused often.

  3. Handle errors gracefully (API rate limits or service downtime).

  4. Ensure secure API keys (store in appsettings or environment variables).

  5. Consider asynchronous calls for a better user experience.

Conclusion

Adding AI/ML features in your full-stack app makes it smarter, interactive, and modern. With ASP.NET Core backend, Angular frontend, and cloud AI services or custom ML models, you can implement chatbots, recommendations, sentiment analysis, and more.