Many organizations already have ASP.NET Core APIs that handle important business operations. These applications may manage customers, orders, products, payments, reports, or internal workflows. As AI becomes more common, development teams want to introduce features such as intelligent search, automated summaries, customer support assistants, and natural-language queries.
However, adding AI does not mean rebuilding an existing application.
A common mistake is to create a separate AI application, move existing business logic into it, and introduce new APIs for operations that already work. This increases maintenance costs and creates unnecessary complexity.
A better approach is to introduce AI as an additional capability within the existing architecture. Keep current endpoints, services, database operations, authentication, and business rules intact. Add a dedicated AI service layer that uses existing application services and communicates with an AI model when required.
In this article, we will explore how to add AI capabilities to an existing ASP.NET Core API incrementally using Microsoft.Extensions.AI, dependency injection, and a clean service architecture.
Why You Should Not Rewrite an Existing API for AI
Consider an existing e-commerce application built with ASP.NET Core.
It already provides endpoints for retrieving products, checking order status, managing customers, and processing orders.
The development team now wants to introduce an AI-powered customer assistant that can answer questions such as:
- Which products are available under a specific budget?
- What is the current status of my order?
- Summarize my recent purchases.
- Which products are similar to the one I purchased?
A complete rewrite is unnecessary because most of the required business operations already exist.
The existing application may look like this:
ASP.NET Core API
|
v
Controllers
|
v
Business Services
|
v
Repositories
|
v
Database
Instead of replacing this architecture, introduce an AI layer:
ASP.NET Core API
|
+-----------+-----------+
| |
v v
Existing APIs AI Endpoints
| |
v v
Business Services AI Application Service
| |
v v
Database IChatClient
|
v
AI Model
The AI service can reuse existing business services to retrieve trusted application data.
This approach provides several advantages:
- Existing API consumers continue working.
- Business rules remain in their current services.
- AI functionality can be developed independently.
- The model provider can be changed without rewriting controllers.
- Existing authentication and authorization mechanisms can be reused.
- AI features can be introduced gradually.
Understanding the Existing Application
Before introducing AI, identify the responsibilities already handled by the application.
For example, an existing application may have the following structure:
ECommerceApi/
│
├── Controllers/
│ ├── ProductsController.cs
│ └── OrdersController.cs
│
├── Services/
│ ├── ProductService.cs
│ └── OrderService.cs
│
├── Repositories/
│ ├── ProductRepository.cs
│ └── OrderRepository.cs
│
├── Models/
│
└── Program.cs
Suppose ProductService already provides a method for retrieving products within a price range.
public sealed class ProductService
{
private readonly IProductRepository _repository;
public ProductService(IProductRepository repository)
{
_repository = repository;
}
public Task<List<Product>> GetProductsByPriceAsync(
decimal maxPrice,
CancellationToken cancellationToken)
{
return _repository.GetProductsByPriceAsync(
maxPrice,
cancellationToken);
}
}
This service already contains the business operation required by the new AI feature.
There is no reason to create another repository or duplicate the database query inside an AI controller.
Instead, the AI feature should use ProductService through dependency injection.
This is an important architectural principle: AI should extend existing business capabilities rather than create competing implementations of them.
Adding Microsoft.Extensions.AI
Microsoft.Extensions.AI provides a common abstraction for communicating with different AI providers.
Its IChatClient interface allows application services to interact with chat models without depending directly on a specific provider SDK.
Install the package:
dotnet add package Microsoft.Extensions.AI
For this example, we will use Ollama as the local model provider.
Install its integration package:
dotnet add package OllamaSharp
You can use another provider by registering an appropriate IChatClient implementation.
For example, OpenAI integration can use the Microsoft.Extensions.AI.OpenAI package.
dotnet add package Microsoft.Extensions.AI.OpenAI
The important point is that the AI application service will depend on IChatClient, not OllamaSharp or an OpenAI-specific client.
Configuring the AI Provider
Add the following configuration to appsettings.json:
{
"AI": {
"Provider": "Ollama",
"Model": "llama3.2",
"Endpoint": "http://localhost:11434"
}
}
The configuration defines the selected provider, model, and endpoint.
For local development, the application can connect to an Ollama server running on the development machine.
For production, configuration should come from the appropriate environment or secret-management system. Cloud API keys should never be committed to source control.
Create an AIOptions class:
public sealed class AIOptions
{
public string Provider { get; set; } = "Ollama";
public string Model { get; set; } = "llama3.2";
public string Endpoint { get; set; } =
"http://localhost:11434";
}
This class provides strongly typed access to AI configuration.
It also makes it easier to validate settings during application startup.
Registering the AI Client Without Changing Existing Services
The next step is registering IChatClient in the existing application's dependency injection container.
Update Program.cs:
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using OllamaSharp;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<AIOptions>(
builder.Configuration.GetSection("AI"));
builder.Services.AddSingleton<IChatClient>(serviceProvider =>
{
var options = serviceProvider
.GetRequiredService<IOptions<AIOptions>>()
.Value;
return new OllamaApiClient(
new Uri(options.Endpoint),
options.Model);
});
builder.Services.AddScoped<ProductService>();
builder.Services.AddScoped<OrderService>();
builder.Services.AddScoped<AIApplicationService>();
var app = builder.Build();
app.MapControllers();
app.Run();
The existing services remain registered as before. The only new dependency is IChatClient and the AI application service.
The singleton lifetime shown here assumes the selected client implementation supports concurrent use and that its disposal behavior is compatible with this registration. Check the provider implementation's documentation before choosing a lifetime.
If the application already uses extension methods for dependency registration, keep the AI registrations in a separate extension method instead of making Program.cs increasingly large.
Creating an AI Application Service
The AI application service acts as a bridge between the existing business services and the model.
Create AIApplicationService.cs:
using Microsoft.Extensions.AI;
public sealed class AIApplicationService
{
private readonly IChatClient _chatClient;
private readonly ProductService _productService;
public AIApplicationService(
IChatClient chatClient,
ProductService productService)
{
_chatClient = chatClient;
_productService = productService;
}
public async Task<string> FindProductsAsync(
decimal maxPrice,
CancellationToken cancellationToken)
{
var products = await _productService
.GetProductsByPriceAsync(
maxPrice,
cancellationToken);
if (products.Count == 0)
{
return "No products were found within your budget.";
}
var productData = string.Join(
"\n",
products.Select(product =>
$"{product.Name}: {product.Price}"));
var messages = new List<ChatMessage>
{
new(
ChatRole.System,
"You are a shopping assistant. " +
"Recommend products only from the supplied data. " +
"Do not invent product names or prices."
),
new(
ChatRole.User,
$"Recommend suitable products under {maxPrice}. " +
$"Available products:\n{productData}"
)
};
var response = await _chatClient.GetResponseAsync(
messages,
cancellationToken: cancellationToken);
return response.Text ?? string.Empty;
}
}
This implementation follows an important separation of responsibilities.
ProductService retrieves product information using the existing business logic.
AIApplicationService prepares the data and sends it to the model for a natural-language recommendation.
The model does not directly access the database, and the existing product repository does not need to know that AI is being used.
For production applications, avoid sending unnecessary customer or business data to the model. Apply authorization before retrieving records, minimize the information included in prompts, and consider whether the selected provider is approved to process that data.
Also remember that asking a model to use only supplied information is not a guarantee against incorrect responses. Validate important recommendations and factual claims against application data.
Adding a New AI Endpoint
Now expose the AI functionality through a new API endpoint.
If the existing application uses controllers, create AIController.cs:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/ai")]
public sealed class AIController : ControllerBase
{
private readonly AIApplicationService _aiService;
public AIController(AIApplicationService aiService)
{
_aiService = aiService;
}
[HttpGet("product-recommendations")]
public async Task<IActionResult> GetRecommendations(
[FromQuery] decimal maxPrice,
CancellationToken cancellationToken)
{
if (maxPrice <= 0)
{
return BadRequest(
new { message = "Maximum price must be greater than zero." });
}
var result = await _aiService.FindProductsAsync(
maxPrice,
cancellationToken);
return Ok(new
{
recommendations = result
});
}
}
The endpoint accepts a maximum price and delegates the operation to AIApplicationService.
The existing product API remains unchanged.
For example, an existing endpoint such as GET /api/products continues to return its original response. The new endpoint adds an AI-powered experience without breaking existing consumers.
In a production implementation, add appropriate authorization, rate limiting, request validation, and exception handling. Also consider returning structured recommendation data rather than relying entirely on a free-form text response.
Reusing Existing Business Services With AI Tool Calling
The previous example retrieves product data before sending it to the model.
For more interactive scenarios, the application can expose existing business operations as AI tools.
For example, an assistant may need to retrieve an order status only when a user asks about an order.
Microsoft.Extensions.AI supports function tools through AIFunctionFactory and function-invocation middleware.
A simplified tool definition looks like this:
using Microsoft.Extensions.AI;
var getOrderTool = AIFunctionFactory.Create(
async (
string orderId,
CancellationToken cancellationToken) =>
{
return await orderService.GetOrderAsync(
orderId,
cancellationToken);
},
"get_order",
"Retrieve the status of an order using its order ID.");
The function wraps an existing business operation.
The AI application can make this function available through its chat-client pipeline:
IChatClient toolEnabledClient = new ChatClientBuilder(chatClient)
.UseFunctionInvocation()
.Build();
The exact integration should be configured according to the application's tool-calling design and the selected provider's capabilities.
Tool invocation does not replace application authorization. The order service must still verify that the authenticated user is allowed to access the requested order.
For sensitive operations, use explicit approval and server-side authorization before executing the operation.
Introducing AI Without Breaking Existing API Consumers
One of the most important requirements when adding AI to an existing application is backward compatibility.
Suppose an existing endpoint returns:
{
"id": 101,
"name": "Wireless Headphones",
"price": 2499
}
Do not change this response simply because an AI recommendation feature has been introduced.
Existing mobile applications, web clients, and third-party integrations may depend on the current response structure.
Instead, introduce a separate endpoint or a versioned API contract for the new functionality.
A practical migration strategy looks like this:
| Existing Application Area |
Recommended AI Integration |
| Product APIs |
Add AI-powered product recommendations |
| Order APIs |
Add natural-language order assistance |
| Customer support |
Add an AI assistant using existing support services |
| Reporting APIs |
Add report summaries |
| Search APIs |
Add semantic search or natural-language filtering |
| Authentication |
Reuse existing identity and authorization services |
| Database access |
Reuse existing repositories and business services |
This approach allows teams to release AI features incrementally without changing established application contracts.
Handling AI Failures Independently
AI providers can experience timeouts, rate limits, authentication failures, and temporary outages.
These failures should not affect unrelated existing API operations.
For example, if an AI recommendation endpoint fails, the normal product listing endpoint should continue working.
Use separate exception handling and appropriate timeout policies for AI operations.
try
{
var result = await _aiService.FindProductsAsync(
maxPrice,
cancellationToken);
return Ok(new { recommendations = result });
}
catch (OperationCanceledException)
when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (TimeoutException)
{
return StatusCode(
StatusCodes.Status504GatewayTimeout,
new { message = "The AI service took too long to respond." });
}
catch (Exception)
{
return StatusCode(
StatusCodes.Status503ServiceUnavailable,
new { message = "AI recommendations are temporarily unavailable." });
}
This example illustrates the API boundary. A complete implementation should use centralized exception handling and log the original exception with a correlation identifier.
Do not catch every exception and return a successful response containing an empty recommendation. That hides failures and makes monitoring difficult.
For business-critical functionality, provide a non-AI fallback where possible. For example, the existing product filtering service can still return matching products even when the AI recommendation service is unavailable.
Best Practices for Adding AI to Existing APIs
- Keep existing controllers, repositories, and business services intact.
- Introduce AI through a dedicated application service.
- Depend on IChatClient rather than a provider-specific SDK in business logic.
- Register AI dependencies through the existing dependency injection container.
- Keep model names, endpoints, and credentials in configuration.
- Reuse existing authorization and validation rules.
- Avoid sending unnecessary business or customer data to external models.
- Keep AI endpoints separate from existing API contracts when appropriate.
- Apply timeouts, cancellation, rate limiting, and controlled error handling.
- Monitor AI requests independently from ordinary API operations.
- Test AI application logic using fake model responses.
- Introduce new AI features gradually and measure their actual value.
Advantages and Disadvantages
Advantages
- Existing application architecture remains intact.
- Existing API consumers do not need to be rewritten.
- AI capabilities can be introduced one feature at a time.
- Existing business services and data access logic can be reused.
- Provider changes are easier when using common abstractions.
- AI failures can be isolated from core application operations.
- Development and maintenance costs can be controlled.
Disadvantages
- Existing services may need refactoring if their responsibilities are not clearly separated.
- AI integration introduces additional configuration and operational requirements.
- Model responses may be inconsistent and require validation.
- Sending application data to a model introduces privacy and compliance considerations.
- AI requests can increase infrastructure costs and response times.
- Tool calling requires additional authorization and execution safeguards.
Summary
Adding AI to an existing ASP.NET Core API does not require rewriting the application. Most applications already contain business services, repositories, authentication mechanisms, and APIs that can support new AI-powered features.
A better approach is to introduce a dedicated AI application service, register IChatClient through dependency injection, and reuse existing business services to retrieve and process application data.
Microsoft.Extensions.AI provides a common abstraction that helps keep application code independent of a specific model provider. New AI endpoints can then be introduced without changing existing API contracts.
The most important principle is to treat AI as an additional application capability, not a replacement for the existing architecture. Keep business rules in application services, enforce authorization outside the model, isolate AI failures, and introduce new functionality incrementally.
Join the conversation! Your thoughts help the community grow.