Modern web applications increasingly rely on specialized or self-hosted AI models—ranging from fine-tuned domain classifiers and internal enterprise LLMs to local inference endpoints—rather than a single general-purpose cloud API. In an ASP.NET Core MVC application, wiring a custom model directly into controllers or views quickly creates tight coupling, inconsistent error handling, and fragile JSON serialization code.
By implementing IChatClient from Microsoft.Extensions.AI, you can wrap any custom model behind a standard .NET abstraction. Your MVC controllers, services, and Razor views remain completely independent of the underlying model server while still benefiting from dependency injection, logging, and composable middleware.
1. Architecture Overview
A clean integration separates transport and payload mapping from application logic:
MVC Layer (
Controllers&Views): Collects user prompts or task parameters, invokes an application service orIChatClient, and renders results without knowing how the model is hosted.Custom Adapter (
CustomModelChatClient): ImplementsIChatClient, translatesChatMessageandChatOptionsinto your custom model endpoint's request schema, and maps the response back toChatResponse.HTTP & DI Layer (
Program.cs): UsesIHttpClientFactory(AddHttpClient<T>) for connection pooling and timeouts, then registersIChatClientwith middleware such asUseLogging().
Tip: If your custom model server already exposes an OpenAI-compatible chat endpoint (for example, vLLM or LocalAI), you can point
OpenAIClientat that base URL first. Writing a customIChatClientis ideal when your endpoint uses proprietary request/response fields, custom headers, or internal inference gateways.
2. Project Setup and NuGet Packages
Create or open an ASP.NET Core MVC project (.NET 8 or .NET 9+) and install Microsoft.Extensions.AI:
Bash
dotnet add package Microsoft.Extensions.AIThis single package brings in IChatClient, ChatMessage, ChatResponse, ChatOptions, and ChatClientBuilder middleware extensions.
3. Implementing a Custom IChatClient
Create Infrastructure/CustomModelChatClient.cs to bridge Microsoft.Extensions.AI with your custom model HTTP API.
C#
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Text.Json.Serialization;
using Microsoft.Extensions.AI;
namespace CustomModelMvcApp.Infrastructure;
public sealed class CustomModelChatClient : IChatClient
{
private readonly HttpClient _httpClient;
private readonly string _defaultModel;
public CustomModelChatClient(HttpClient httpClient, string defaultModel)
{
_httpClient = httpClient;
_defaultModel = defaultModel;
}
public ChatClientMetadata Metadata => new(
providerName: "CustomModelEndpoint",
providerUri: _httpClient.BaseAddress,
defaultModelId: _defaultModel);
public async Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
CancellationToken cancellationToken = default)
{
string modelId = options?.ModelId ?? _defaultModel;
var requestPayload = new CustomModelRequest
{
Model = modelId,
Temperature = options?.Temperature ?? 0.2f,
MaxTokens = options?.MaxOutputTokens ?? 512,
Messages = messages.Select(m => new CustomMessageDto
{
Role = m.Role.Value,
Content = m.Text ?? string.Empty
}).ToList()
};
using HttpResponseMessage response = await _httpClient.PostAsJsonAsync(
"/v1/custom-chat",
requestPayload,
cancellationToken);
response.EnsureSuccessStatusCode();
CustomModelResponse? result = await response.Content
.ReadFromJsonAsync<CustomModelResponse>(cancellationToken);
string content = result?.ResponseText ?? string.Empty;
var assistantMessage = new ChatMessage(ChatRole.Assistant, content);
return new ChatResponse(assistantMessage)
{
ModelId = modelId,
Usage = new UsageDetails
{
InputTokenCount = result?.InputTokens,
OutputTokenCount = result?.OutputTokens,
TotalTokenCount = (result?.InputTokens ?? 0) + (result?.OutputTokens ?? 0)
}
};
}
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Replace with chunked/SSE reading if your custom endpoint streams tokens incrementally.
ChatResponse response = await GetResponseAsync(messages, options, cancellationToken);
yield return new ChatResponseUpdate(ChatRole.Assistant, response.Text)
{
ModelId = response.ModelId
};
}
public object? GetService(Type serviceType, object? serviceKey = null) =>
serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null;
public void Dispose()
{
// HttpClient lifetime is managed by IHttpClientFactory.
}
private sealed class CustomModelRequest
{
[JsonPropertyName("model")]
public string Model { get; set; } = string.Empty;
[JsonPropertyName("temperature")]
public float Temperature { get; set; }
[JsonPropertyName("max_tokens")]
public int MaxTokens { get; set; }
[JsonPropertyName("messages")]
public List<CustomMessageDto> Messages { get; set; } = [];
}
private sealed class CustomMessageDto
{
[JsonPropertyName("role")]
public string Role { get; set; } = string.Empty;
[JsonPropertyName("content")]
public string Content { get; set; } = string.Empty;
}
private sealed class CustomModelResponse
{
[JsonPropertyName("response_text")]
public string? ResponseText { get; set; }
[JsonPropertyName("input_tokens")]
public int? InputTokens { get; set; }
[JsonPropertyName("output_tokens")]
public int? OutputTokens { get; set; }
}
}4. Configuring Dependency Injection in Program.cs
Register CustomModelChatClient through AddHttpClient<T> so sockets are pooled properly and timeouts are explicitly controlled. Then wrap it with ChatClientBuilder to enable logging.
C#
using System.Net.Http.Headers;
using CustomModelMvcApp.Infrastructure;
using Microsoft.Extensions.AI;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
string baseUrl = builder.Configuration["CustomAi:Endpoint"]
?? throw new InvalidOperationException("Configuration value 'CustomAi:Endpoint' is required.");
string modelName = builder.Configuration["CustomAi:ModelName"] ?? "custom-domain-model";
string? apiKey = builder.Configuration["CustomAi:ApiKey"];
builder.Services.AddHttpClient<CustomModelChatClient>(client =>
{
client.BaseAddress = new Uri(baseUrl);
client.Timeout = TimeSpan.FromSeconds(60);
if (!string.IsNullOrWhiteSpace(apiKey))
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
}
});
builder.Services.AddChatClient(sp =>
{
var client = sp.GetRequiredService<CustomModelChatClient>();
return new ChatClientBuilder(client)
.UseLogging()
.Build();
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=ModelWorkbench}/{action=Index}/{id?}");
app.Run();Store sensitive tokens in User Secrets during local development (dotnet user-secrets set "CustomAi:ApiKey" "your-token") or in environment variables in production rather than committing secrets to source control.
5. Building the MVC Model, Controller, and Razor View
ViewModel (Models/WorkbenchViewModel.cs)
C#
using System.ComponentModel.DataAnnotations;
namespace CustomModelMvcApp.Models;
public sealed class WorkbenchViewModel
{
[Display(Name = "System Instructions")]
public string? SystemPrompt { get; set; }
[Required(ErrorMessage = "Please enter an input prompt.")]
[Display(Name = "Prompt")]
public string UserPrompt { get; set; } = string.Empty;
[Range(0.0, 2.0)]
public float Temperature { get; set; } = 0.2f;
public string? Output { get; set; }
public string? ErrorMessage { get; set; }
}Controller (Controllers/ModelWorkbenchController.cs)
Inject IChatClient and handle transient HTTP/network issues gracefully so the UI stays responsive when a model server is slow or unreachable.
C#
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.AI;
using CustomModelMvcApp.Models;
namespace CustomModelMvcApp.Controllers;
public sealed class ModelWorkbenchController : Controller
{
private readonly IChatClient _chatClient;
private readonly ILogger<ModelWorkbenchController> _logger;
public ModelWorkbenchController(
IChatClient chatClient,
ILogger<ModelWorkbenchController> logger)
{
_chatClient = chatClient;
_logger = logger;
}
[HttpGet]
public IActionResult Index()
{
return View(new WorkbenchViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(
WorkbenchViewModel model,
CancellationToken cancellationToken)
{
if (!ModelState.IsValid)
{
return View(model);
}
List<ChatMessage> messages = [];
if (!string.IsNullOrWhiteSpace(model.SystemPrompt))
{
messages.Add(new ChatMessage(ChatRole.System, model.SystemPrompt));
}
messages.Add(new ChatMessage(ChatRole.User, model.UserPrompt));
ChatOptions options = new()
{
Temperature = model.Temperature,
MaxOutputTokens = 800
};
try
{
ChatResponse response = await _chatClient.GetResponseAsync(
messages,
options,
cancellationToken);
model.Output = response.Text;
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "Failed to reach custom AI model endpoint.");
model.ErrorMessage = "The custom model service is currently unavailable. Please try again.";
}
catch (TaskCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
_logger.LogWarning(ex, "Custom AI model request timed out.");
model.ErrorMessage = "The request timed out while waiting for the custom model.";
}
return View(model);
}
}Razor View (Views/ModelWorkbench/Index.cshtml)
Razor CSHTML
@model CustomModelMvcApp.Models.WorkbenchViewModel
@{
ViewData["Title"] = "Custom Model Workbench";
}
<h2>Custom AI Model Workbench</h2>
<form asp-action="Index" method="post">
@Html.AntiForgeryToken()
<div class="mb-3">
<label asp-for="SystemPrompt" class="form-label"></label>
<input asp-for="SystemPrompt" class="form-control"
placeholder="Optional role or formatting instructions..." />
</div>
<div class="mb-3">
<label asp-for="Temperature" class="form-label"></label>
<input asp-for="Temperature" type="number" step="0.1" min="0" max="2" class="form-control" />
<span asp-validation-for="Temperature" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="UserPrompt" class="form-label"></label>
<textarea asp-for="UserPrompt" class="form-control" rows="6"
placeholder="Enter text or instructions for your custom model..."></textarea>
<span asp-validation-for="UserPrompt" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Run Model</button>
</form>
@if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<div class="alert alert-danger mt-4" role="alert">
@Model.ErrorMessage
</div>
}
@if (!string.IsNullOrWhiteSpace(Model.Output))
{
<hr />
<h4>Model Output</h4>
<div class="card card-body bg-light">
<pre class="mb-0" style="white-space: pre-wrap;">@Model.Output</pre>
</div>
}6. Best Practices for Production Deployments
Area | Recommendation |
Layering | Keep |
Timeouts & Retries | Custom models often experience cold starts or queue spikes; set realistic |
Multiple Models | Register multiple |
Observability | Correlate requests with correlation/trace IDs and log token usage ( |
Summary
Wrapping a custom AI model behind IChatClient gives an ASP.NET Core MVC application a clean, maintainable seam between web requests and model inference. Whether your custom model evolves into a different internal endpoint, a local runtime, or an additional specialized model, your MVC controllers and views can continue consuming IChatClient with minimal disruption.

Join the conversation! Your thoughts help the community grow.