ASP.NET Core  

How to Use Microsoft.Extensions.AI to Add AI to ASP.NET Core

Introduction

Artificial Intelligence is becoming a key part of modern applications. From chatbots to smart search and content generation, AI can significantly improve user experience and business value.

In the .NET ecosystem, Microsoft has introduced Microsoft.Extensions.AI (MEAI), a simple and flexible way to integrate AI capabilities into your applications. If you already have an ASP.NET Core app, you don’t need to rebuild everything—you can easily plug AI features into your existing system.

In this article, we will learn how to use Microsoft.Extensions.AI in an ASP.NET Core application in simple steps, with practical examples and real-world use cases.

What Is Microsoft.Extensions.AI (MEAI)?

Microsoft.Extensions.AI is a library that provides a unified and structured way to work with AI services in .NET applications.

It helps you:

  • Connect to AI models (like OpenAI or Azure AI)

  • Manage prompts and responses

  • Use dependency injection for AI services

  • Build scalable and maintainable AI features

Why Use MEAI in ASP.NET Core?

Easy Integration

You can add AI features without major changes to your existing architecture.

Clean Architecture

MEAI works well with dependency injection, making your code modular and testable.

Flexibility

You can switch between different AI providers without changing your core logic.

Enterprise Ready

It supports logging, configuration, and scalability.

Step 1: Install Required Packages

First, install the required NuGet packages:

dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI

These packages allow you to connect your app with AI services.

Step 2: Configure AI Services in Program.cs

In your ASP.NET Core app, register AI services using dependency injection.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAI(options =>
{
    options.UseOpenAI("your-api-key");
});

var app = builder.Build();

This sets up the AI service globally.

Step 3: Create an AI Service Class

Create a service to interact with AI models.

using Microsoft.Extensions.AI;

public class AIService
{
    private readonly IChatClient _chatClient;

    public AIService(IChatClient chatClient)
    {
        _chatClient = chatClient;
    }

    public async Task<string> AskAsync(string question)
    {
        var response = await _chatClient.GetResponseAsync(question);
        return response.Text;
    }
}

This service handles all AI-related logic.

Step 4: Register the Service

builder.Services.AddScoped<AIService>();

Now your AI service is ready to use.

Step 5: Use AI in a Controller

You can now use AI inside your ASP.NET Core controllers.

[ApiController]
[Route("api/ai")]
public class AIController : ControllerBase
{
    private readonly AIService _aiService;

    public AIController(AIService aiService)
    {
        _aiService = aiService;
    }

    [HttpGet("ask")]
    public async Task<IActionResult> Ask(string query)
    {
        var result = await _aiService.AskAsync(query);
        return Ok(result);
    }
}

Now your app can respond to AI queries.

Step 6: Add a Simple UI (Optional)

You can connect this API to a frontend (Blazor, React, or Razor Pages).

Example (Razor):

<input id="question" />
<button onclick="askAI()">Ask</button>

<script>
async function askAI() {
    const q = document.getElementById('question').value;
    const res = await fetch(`/api/ai/ask?query=${q}`);
    const data = await res.text();
    alert(data);
}
</script>

Common AI Features You Can Add

Chatbot

Allow users to ask questions and get instant answers.

Smart Search

Use AI to understand user intent and improve search results.

Content Generation

Generate descriptions, emails, or summaries automatically.

Code Assistance

Help developers with code suggestions inside internal tools.

Best Practices for Using MEAI

Secure API Keys

Always store API keys in configuration files or environment variables.

Use Caching

Cache responses to reduce API calls and cost.

Handle Errors Gracefully

AI services may fail—always add fallback logic.

Optimize Prompts

Clear and structured prompts give better results.

Real-World Example

Imagine an e-commerce application:

  • Users can ask product-related questions

  • AI suggests products based on queries

  • Generates product descriptions automatically

This improves user engagement and conversion rates.

When Should You Use MEAI?

When You Want to Add AI Quickly

MEAI simplifies integration without complex setup.

When Building Enterprise Applications

It supports scalable and maintainable architecture.

When You Need Flexibility

You can switch AI providers easily.

When You Should Avoid It

Small Applications Without AI Needs

If AI is not required, adding it increases complexity.

High-Cost Sensitivity Projects

AI APIs may increase operational cost.

Summary

Microsoft.Extensions.AI (MEAI) provides a simple and powerful way to integrate AI into ASP.NET Core applications. With built-in support for dependency injection, flexibility across providers, and clean architecture, it allows developers to add intelligent features like chatbots, smart search, and content generation and efficiently. By following best practices and understanding your use case, you can build scalable and modern AI-powered applications in .NET.