
Previous article: ASP.NET Core Frontend Fusion: Integrating React, Angular & Vue.js - Complete Guide (Part - 23 of 40)
Table of Contents
Introduction to AI in ASP.NET Core
Setting Up Your AI-Ready Environment
ML.NET Fundamentals
Building Predictive Models with ML.NET
OpenAI Integration Basics
Advanced AI Scenarios
Real-World Case Studies
Best Practices & Performance Optimization
Production Deployment
Future of AI in Web Development
1. Introduction to AI in ASP.NET Core
The AI Revolution in Web Development
Artificial Intelligence has transformed from a niche technology to a fundamental component of modern web applications. ASP.NET Core developers now have unprecedented access to AI capabilities through frameworks like ML.NET and cloud services like OpenAI.
Why Integrate AI in Your ASP.NET Core Applications?
Enhanced User Experience
Personalized content recommendations
Intelligent search capabilities
Predictive user behavior analysis
Automated customer support
Business Value
Improved decision-making through data insights
Automated repetitive tasks
Enhanced security through anomaly detection
Competitive advantage in the market
Real-World AI Success Stories
Netflix: Uses AI for content recommendation, resulting in 80% of watched content coming from recommendations.
Amazon: Implements AI for product recommendations, driving 35% of total revenue.
Spotify: Leverages machine learning for personalized playlists, increasing user engagement by 30%.
2. Setting Up Your AI-Ready Environment
Prerequisites and Tools
// Required NuGet Packages
<PackageReference Include="Microsoft.ML" Version="3.0.1" />
<PackageReference Include="Microsoft.ML.Vision" Version="3.0.1" />
<PackageReference Include="Microsoft.ML.TimeSeries" Version="3.0.1" />
<PackageReference Include="OpenAI" Version="1.7.2" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
Environment Configuration
// Program.cs - AI Services Registration
using Microsoft.ML;
using OpenAI_API;
var builder = WebApplication.CreateBuilder(args);
// ML.NET Context
builder.Services.AddSingleton<MLContext>(new MLContext(seed: 0));
// OpenAI Configuration
builder.Services.AddSingleton<OpenAIAPI>(provider =>
new OpenAIAPI(builder.Configuration["OpenAI:ApiKey"]));
// HTTP Client for AI Services
builder.Services.AddHttpClient("AIServices", client =>
{
client.Timeout = TimeSpan.FromSeconds(30);
});
// Custom AI Services
builder.Services.AddScoped<IPredictionService, PredictionService>();
builder.Services.AddScoped<INLPService, NLPService>();
builder.Services.AddScoped<IImageAIService, ImageAIService>();
var app = builder.Build();
Configuration Files
// appsettings.json
{
"OpenAI": {
"ApiKey": "your-openai-api-key",
"Organization": "your-organization-id",
"MaxTokens": 150,
"Temperature": 0.7
},
"MLNET": {
"ModelPath": "Models/",
"TrainingDataPath": "Data/Training/",
"RetrainIntervalHours": 24
},
"AISettings": {
"CacheDuration": 30,
"FallbackEnabled": true,
"RateLimit": 100
}
}
3. ML.NET Fundamentals
Understanding ML.NET Architecture
ML.NET is Microsoft's open-source, cross-platform machine learning framework specifically designed for .NET developers.
Key Components
// Basic ML.NET Pipeline Structure
public class MLNetBasicPipeline
{
private readonly MLContext _mlContext;
public MLNetBasicPipeline()
{
_mlContext = new MLContext(seed: 0);
}
public ITransformer TrainModel<TData>(IEnumerable<TData> trainingData)
where TData : class
{
// Load data
var dataView = _mlContext.Data.LoadFromEnumerable(trainingData);
// Define pipeline
var pipeline = _mlContext.Transforms
.Conversion.MapValueToKey("Label")
.Append(_mlContext.Transforms.Concatenate("Features",
nameof(TData.Features)))
.Append(_mlContext.MulticlassClassification.Trainers
.SdcaMaximumEntropy("Label", "Features"))
.Append(_mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
// Train model
return pipeline.Fit(dataView);
}
}
Data Models for Machine Learning
// Real Estate Price Prediction Model
public class RealEstateData
{
[LoadColumn(0)]
public float SizeSqFt { get; set; }
[LoadColumn(1)]
public float Bedrooms { get; set; }
[LoadColumn(2)]
public float Bathrooms { get; set; }
[LoadColumn(3)]
public float YearBuilt { get; set; }
[LoadColumn(4)]
public float LocationScore { get; set; }
[LoadColumn(5)]
public float Price { get; set; } // Label
}
public class RealEstatePrediction
{
[ColumnName("Score")]
public float Price { get; set; }
}
4. Building Predictive Models with ML.NET
Real Estate Price Prediction System
// Complete Real Estate Prediction Service
public class RealEstatePredictionService
{
private readonly MLContext _mlContext;
private ITransformer _model;
private readonly string _modelPath;
public RealEstatePredictionService(MLContext mlContext, IWebHostEnvironment env)
{
_mlContext = mlContext;
_modelPath = Path.Combine(env.ContentRootPath, "Models", "realestate-model.zip");
LoadOrTrainModel();
}
private void LoadOrTrainModel()
{
if (File.Exists(_modelPath))
{
_model = _mlContext.Model.Load(_modelPath, out _);
}
else
{
TrainModel();
}
}
private void TrainModel()
{
// Sample training data - in real scenario, load from database
var trainingData = new List<RealEstateData>
{
new() { SizeSqFt = 1500, Bedrooms = 3, Bathrooms = 2, YearBuilt = 2000, LocationScore = 8, Price = 350000 },
new() { SizeSqFt = 2000, Bedrooms = 4, Bathrooms = 3, YearBuilt = 2010, LocationScore = 9, Price = 500000 },
new() { SizeSqFt = 1200, Bedrooms = 2, Bathrooms = 1, YearBuilt = 1990, LocationScore = 6, Price = 250000 },
// Add more training data...
};
var dataView = _mlContext.Data.LoadFromEnumerable(trainingData);
var pipeline = _mlContext.Transforms.Concatenate("Features",
nameof(RealEstateData.SizeSqFt),
nameof(RealEstateData.Bedrooms),
nameof(RealEstateData.Bathrooms),
nameof(RealEstateData.YearBuilt),
nameof(RealEstateData.LocationScore))
.Append(_mlContext.Regression.Trainers.Sdca(
labelColumnName: nameof(RealEstateData.Price),
maximumNumberOfIterations: 100));
_model = pipeline.Fit(dataView);
// Save the model
var directory = Path.GetDirectoryName(_modelPath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
_mlContext.Model.Save(_model, dataView.Schema, _modelPath);
}
public async Task<RealEstatePredictionResult> PredictAsync(RealEstateInput input)
{
var predictionEngine = _mlContext.Model
.CreatePredictionEngine<RealEstateData, RealEstatePrediction>(_model);
var data = new RealEstateData
{
SizeSqFt = input.SizeSqFt,
Bedrooms = input.Bedrooms,
Bathrooms = input.Bathrooms,
YearBuilt = input.YearBuilt,
LocationScore = input.LocationScore
};
var prediction = predictionEngine.Predict(data);
return new RealEstatePredictionResult
{
PredictedPrice = prediction.Price,
Confidence = CalculateConfidence(prediction.Price),
Recommendations = GenerateRecommendations(input, prediction.Price)
};
}
private float CalculateConfidence(float predictedPrice)
{
// Implement confidence calculation logic
return 0.85f; // Example confidence score
}
private List<string> GenerateRecommendations(RealEstateInput input, float predictedPrice)
{
var recommendations = new List<string>();
if (input.YearBuilt < 1980)
recommendations.Add("Consider renovation budget for older property");
if (predictedPrice > 1000000)
recommendations.Add("Premium property - target luxury market");
return recommendations;
}
}
// Controller Implementation
[ApiController]
[Route("api/[controller]")]
public class RealEstateController : ControllerBase
{
private readonly RealEstatePredictionService _predictionService;
public RealEstateController(RealEstatePredictionService predictionService)
{
_predictionService = predictionService;
}
[HttpPost("predict")]
public async Task<ActionResult<RealEstatePredictionResult>> Predict(RealEstateInput input)
{
try
{
var result = await _predictionService.PredictAsync(input);
return Ok(result);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Prediction failed", details = ex.Message });
}
}
}
E-commerce Product Recommendation Engine
// Product Recommendation System
public class ProductRecommendationService
{
private readonly MLContext _mlContext;
private ITransformer _model;
private readonly List<ProductInteraction> _interactionData;
public ProductRecommendationService(MLContext mlContext)
{
_mlContext = mlContext;
_interactionData = LoadInteractionData();
TrainModel();
}
public class ProductInteraction
{
public uint UserID { get; set; }
public uint ProductID { get; set; }
public float Rating { get; set; }
public DateTime InteractionTime { get; set; }
public string InteractionType { get; set; } // View, Purchase, Cart, etc.
}
public class ProductPrediction
{
public float Score { get; set; }
public uint ProductID { get; set; }
}
private List<ProductInteraction> LoadInteractionData()
{
// In real application, load from database
return new List<ProductInteraction>
{
new() { UserID = 1, ProductID = 101, Rating = 5, InteractionType = "Purchase" },
new() { UserID = 1, ProductID = 102, Rating = 4, InteractionType = "View" },
new() { UserID = 2, ProductID = 101, Rating = 3, InteractionType = "Purchase" },
new() { UserID = 2, ProductID = 103, Rating = 5, InteractionType = "Purchase" },
// More sample data...
};
}
private void TrainModel()
{
var trainingData = _mlContext.Data.LoadFromEnumerable(_interactionData);
var options = new MatrixFactorizationTrainer.Options
{
MatrixColumnIndexColumnName = nameof(ProductInteraction.UserID),
MatrixRowIndexColumnName = nameof(ProductInteraction.ProductID),
LabelColumnName = nameof(ProductInteraction.Rating),
NumberOfIterations = 20,
ApproximationRank = 100
};
var pipeline = _mlContext.Recommendation().Trainers.MatrixFactorization(options);
_model = pipeline.Fit(trainingData);
}
public List<ProductRecommendation> GetRecommendations(uint userId, int topK = 5)
{
var allProducts = _interactionData.Select(i => i.ProductID).Distinct();
var recommendations = new List<ProductRecommendation>();
var predictionEngine = _mlContext.Model
.CreatePredictionEngine<ProductInteraction, ProductPrediction>(_model);
foreach (var productId in allProducts)
{
var input = new ProductInteraction
{
UserID = userId,
ProductID = productId
};
var prediction = predictionEngine.Predict(input);
recommendations.Add(new ProductRecommendation
{
ProductID = productId,
Score = prediction.Score,
Confidence = prediction.Score / 5.0f // Normalize to 0-1
});
}
return recommendations
.OrderByDescending(r => r.Score)
.Take(topK)
.ToList();
}
}
// Recommendation Controller
[ApiController]
[Route("api/[controller]")]
public class RecommendationsController : ControllerBase
{
private readonly ProductRecommendationService _recommendationService;
public RecommendationsController(ProductRecommendationService recommendationService)
{
_recommendationService = recommendationService;
}
[HttpGet("user/{userId}")]
public IActionResult GetUserRecommendations(uint userId, [FromQuery] int topK = 5)
{
var recommendations = _recommendationService.GetRecommendations(userId, topK);
return Ok(new { UserId = userId, Recommendations = recommendations });
}
[HttpPost("interaction")]
public IActionResult RecordInteraction([FromBody] ProductInteraction interaction)
{
// Record user interaction for model retraining
// This would typically save to a database
return Ok(new { Message = "Interaction recorded", Interaction = interaction });
}
}
5. OpenAI Integration Basics
Setting Up OpenAI in ASP.NET Core
// OpenAI Service Implementation
public interface IOpenAIService
{
Task<string> GenerateTextAsync(string prompt, string model = "gpt-3.5-turbo");
Task<string> AnalyzeSentimentAsync(string text);
Task<List<string>> GenerateImageDescriptionsAsync(string imageContext);
Task<string> TranslateTextAsync(string text, string targetLanguage);
}
public class OpenAIService : IOpenAIService
{
private readonly OpenAIAPI _openAIClient;
private readonly ILogger<OpenAIService> _logger;
private readonly IConfiguration _configuration;
public OpenAIService(OpenAIAPI openAIClient, ILogger<OpenAIService> logger, IConfiguration configuration)
{
_openAIClient = openAIClient;
_logger = logger;
_configuration = configuration;
}
public async Task<string> GenerateTextAsync(string prompt, string model = "gpt-3.5-turbo")
{
try
{
var completionRequest = new CompletionRequest
{
Prompt = prompt,
Model = model,
MaxTokens = _configuration.GetValue<int>("OpenAI:MaxTokens", 150),
Temperature = _configuration.GetValue<double>("OpenAI:Temperature", 0.7)
};
var result = await _openAIClient.Completions.CreateCompletionAsync(completionRequest);
return result.Completions[0].Text;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating text with OpenAI");
throw new OpenAIServiceException("Text generation failed", ex);
}
}
public async Task<string> AnalyzeSentimentAsync(string text)
{
var prompt = $@"
Analyze the sentiment of the following text and classify it as Positive, Negative, or Neutral.
Also provide a confidence score between 0 and 1.
Text: ""{text}""
Respond in JSON format:
{{
""sentiment"": ""Positive/Negative/Neutral"",
""confidence"": 0.95,
""key_phrases"": [""phrase1"", ""phrase2""]
}}";
var response = await GenerateTextAsync(prompt);
return response;
}
public async Task<List<string>> GenerateImageDescriptionsAsync(string imageContext)
{
var prompt = $@"
Generate 3 creative and engaging descriptions for an image with the following context:
Context: {imageContext}
Requirements:
- Each description should be under 150 characters
- Include relevant keywords
- Be engaging and descriptive
- Format as a JSON array of strings";
var response = await GenerateTextAsync(prompt);
try
{
var descriptions = JsonSerializer.Deserialize<List<string>>(response);
return descriptions ?? new List<string>();
}
catch
{
// Fallback parsing
return response.Split('\n')
.Where(line => !string.IsNullOrWhiteSpace(line))
.Take(3)
.ToList();
}
}
public async Task<string> TranslateTextAsync(string text, string targetLanguage)
{
var prompt = $@"Translate the following text to {targetLanguage}.
Maintain the original meaning and tone.
Text: ""{text}""
Translation:";
return await GenerateTextAsync(prompt);
}
}
// Advanced OpenAI Chat Completion
public class OpenAIChatService
{
private readonly OpenAIAPI _openAIClient;
public OpenAIChatService(OpenAIAPI openAIClient)
{
_openAIClient = openAIClient;
}
public async Task<ChatMessage> SendChatMessageAsync(List<ChatMessage> conversationHistory, string userMessage)
{
var chatRequest = new ChatRequest
{
Model = "gpt-3.5-turbo",
Messages = conversationHistory
.Append(new ChatMessage(ChatMessageRole.User, userMessage))
.ToArray(),
Temperature = 0.7,
MaxTokens = 500
};
var response = await _openAIClient.Chat.CreateChatCompletionAsync(chatRequest);
return response.Choices[0].Message;
}
}
Intelligent Content Generation System
// AI-Powered Content Management
public class AIContentService
{
private readonly IOpenAIService _openAIService;
private readonly ILogger<AIContentService> _logger;
public AIContentService(IOpenAIService openAIService, ILogger<AIContentService> logger)
{
_openAIService = openAIService;
_logger = logger;
}
public async Task<GeneratedContent> GenerateBlogPostAsync(BlogPostRequest request)
{
var prompt = $@"
Generate a comprehensive blog post with the following requirements:
Topic: {request.Topic}
Target Audience: {request.TargetAudience}
Tone: {request.Tone}
Word Count: {request.WordCount}
Key Points to Cover: {string.Join(", ", request.KeyPoints)}
Structure the blog post with:
- Engaging introduction
- Main content with subheadings
- Practical examples
- Conclusion with key takeaways
- 5 relevant meta tags
Format the response as JSON:
{{
""title"": ""Blog Post Title"",
""content"": ""Full blog post content"",
""excerpt"": ""Short excerpt"",
""metaTags"": [""tag1"", ""tag2""],
""readabilityScore"": 0.85
}}";
var generatedText = await _openAIService.GenerateTextAsync(prompt);
try
{
var content = JsonSerializer.Deserialize<GeneratedContent>(generatedText);
content.SEOScore = await CalculateSEOScoreAsync(content.Content);
return content;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to parse generated content");
return new GeneratedContent
{
Title = "Generated Blog Post",
Content = generatedText,
Excerpt = generatedText.Length > 150 ? generatedText[..150] + "..." : generatedText,
MetaTags = new List<string> { request.Topic.ToLower().Replace(" ", "-") }
};
}
}
private async Task<double> CalculateSEOScoreAsync(string content)
{
var prompt = $@"
Analyze the following content for SEO effectiveness and provide a score from 0 to 1.
Consider:
- Keyword density and placement
- Readability
- Content structure
- Engagement potential
Content: {content.Substring(0, Math.Min(1000, content.Length))}
Respond only with the numerical score:";
var scoreText = await _openAIService.GenerateTextAsync(prompt);
return double.TryParse(scoreText, out var score) ? score : 0.7;
}
}
// Content Generation Controller
[ApiController]
[Route("api/[controller]")]
public class ContentController : ControllerBase
{
private readonly AIContentService _contentService;
public ContentController(AIContentService contentService)
{
_contentService = contentService;
}
[HttpPost("generate-blog")]
public async Task<ActionResult<GeneratedContent>> GenerateBlogPost(BlogPostRequest request)
{
try
{
var content = await _contentService.GenerateBlogPostAsync(request);
return Ok(content);
}
catch (Exception ex)
{
return StatusCode(500, new { error = "Content generation failed", details = ex.Message });
}
}
[HttpPost("analyze-seo")]
public async Task<ActionResult<SEOAnalysis>> AnalyzeSEO([FromBody] string content)
{
var analysis = await _contentService.AnalyzeSEOAsync(content);
return Ok(analysis);
}
}
6. Advanced AI Scenarios
Intelligent Customer Support Chatbot
// AI-Powered Customer Support System
public class CustomerSupportService
{
private readonly OpenAIChatService _chatService;
private readonly IProductService _productService;
private readonly IOrderService _orderService;
private readonly Dictionary<string, List<ChatMessage>> _conversations;
public CustomerSupportService(OpenAIChatService chatService, IProductService productService, IOrderService orderService)
{
_chatService = chatService;
_productService = productService;
_orderService = orderService;
_conversations = new Dictionary<string, List<ChatMessage>>();
}
public async Task<SupportResponse> ProcessCustomerQueryAsync(string sessionId, string userMessage)
{
// Initialize or retrieve conversation history
if (!_conversations.ContainsKey(sessionId))
{
_conversations[sessionId] = new List<ChatMessage>
{
new(ChatMessageRole.System, @"
You are an intelligent customer support assistant for an e-commerce company.
Your capabilities include:
- Answering product questions
- Checking order status
- Processing returns and exchanges
- Providing technical support
- Escalating complex issues
Always be helpful, concise, and professional.
If you need specific information, ask clarifying questions.
For order-related queries, you can access order data.
For product questions, you can access product catalog.
")
};
}
var conversation = _conversations[sessionId];
// Enhance message with context
var enhancedMessage = await EnhanceMessageWithContext(userMessage, sessionId);
var response = await _chatService.SendChatMessageAsync(conversation, enhancedMessage);
// Store the conversation
conversation.Add(new ChatMessage(ChatMessageRole.User, userMessage));
conversation.Add(response);
// Extract and execute actions
var actions = await ExtractAndExecuteActions(response.Content, sessionId);
return new SupportResponse
{
Message = response.Content,
Actions = actions,
SuggestedNextSteps = await GenerateSuggestions(conversation),
Confidence = await CalculateResponseConfidence(response.Content)
};
}
private async Task<string> EnhanceMessageWithContext(string userMessage, string sessionId)
{
// Extract intent and entities
var intent = await ClassifyIntent(userMessage);
var entities = await ExtractEntities(userMessage);
var context = new StringBuilder();
context.AppendLine($"User Message: {userMessage}");
context.AppendLine($"Detected Intent: {intent}");
if (entities.Any())
context.AppendLine($"Extracted Entities: {string.Join(", ", entities)}");
// Add relevant data based on intent
if (intent == "order_status")
{
var recentOrders = await _orderService.GetRecentOrdersAsync(sessionId);
if (recentOrders.Any())
{
context.AppendLine("Recent Orders:");
foreach (var order in recentOrders.Take(3))
{
context.AppendLine($"- Order {order.OrderId}: {order.Status}, {order.TotalAmount:C}");
}
}
}
return context.ToString();
}
private async Task<List<SupportAction>> ExtractAndExecuteActions(string aiResponse, string sessionId)
{
var actions = new List<SupportAction>();
// Parse AI response for actionable items
if (aiResponse.Contains("check order status") || aiResponse.Contains("order status"))
{
var orders = await _orderService.GetRecentOrdersAsync(sessionId);
if (orders.Any())
{
actions.Add(new SupportAction
{
Type = "OrderStatus",
Description = "Retrieved order status",
Data = orders.First()
});
}
}
if (aiResponse.Contains("product information") || aiResponse.Contains("product details"))
{
// Extract product mentions and fetch details
var products = await ExtractProductMentions(aiResponse);
foreach (var product in products)
{
var productInfo = await _productService.GetProductAsync(product);
if (productInfo != null)
{
actions.Add(new SupportAction
{
Type = "ProductInfo",
Description = $"Retrieved {productInfo.Name} details",
Data = productInfo
});
}
}
}
return actions;
}
private async Task<string> ClassifyIntent(string message)
{
var prompt = $@"
Classify the customer's intent from the following message:
Message: ""{message}""
Possible intents:
- order_status
- product_inquiry
- return_request
- technical_support
- billing_issue
- general_question
Respond only with the intent classification:";
return await _chatService.SendChatMessageAsync(
new List<ChatMessage> { new(ChatMessageRole.User, prompt) },
prompt);
}
}
// Support Controller with Real-time Features
[ApiController]
[Route("api/[controller]")]
public class SupportController : ControllerBase
{
private readonly CustomerSupportService _supportService;
private readonly IHubContext<SupportHub> _hubContext;
public SupportController(CustomerSupportService supportService, IHubContext<SupportHub> hubContext)
{
_supportService = supportService;
_hubContext = hubContext;
}
[HttpPost("chat")]
public async Task<ActionResult<SupportResponse>> ProcessChatMessage([FromBody] ChatRequest request)
{
var response = await _supportService.ProcessCustomerQueryAsync(request.SessionId, request.Message);
// Broadcast to connected clients (for real-time support dashboards)
await _hubContext.Clients.Group("support-agents")
.SendAsync("NewSupportInteraction", request.SessionId, request.Message, response);
return Ok(response);
}
[HttpGet("session/{sessionId}/history")]
public IActionResult GetConversationHistory(string sessionId)
{
// Return conversation history (in real app, store in database)
return Ok(new { SessionId = sessionId, History = "Conversation history" });
}
}

Join the conversation! Your thoughts help the community grow.