The integration of advanced open-weights reasoning models like DeepSeek-V4 into enterprise architectures provides organizations with high-performance, cost-effective artificial intelligence capabilities. By leveraging Microsoft Foundry (formerly Azure AI Foundry), engineering teams can natively deploy, govern, and scale DeepSeek models on trusted Azure cloud infrastructure.
This comprehensive guide walks through the end-to-end process of provisioning a DeepSeek-V4 model in Microsoft Foundry through the Azure Portal and consuming it securely within an ASP.NET Core MVC application using the official OpenAI .NET SDK.
Phase 1: Provisioning Microsoft Foundry & Deploying DeepSeek-V4
The first phase involves setting up the underlying Azure AI resource management plane and deploying the model through the Microsoft Foundry portal.
Step 1: Create the Foundry Resource in Azure Portal
Sign in to the Azure Portal (portal.azure.com) and click + Create a resource.
Search for Microsoft Foundry (or Azure AI Services) and select Create.
Configure the Basics tab:
Subscription & Resource Group: Select your target subscription and resource group.
Instance Name: Provide a globally unique name (e.g., foundry-abaengine-prod).
Region: Choose a region supporting DeepSeek catalog deployments (such as East US or East US 2).
Default Project Name: Set your primary project name (e.g., foundry-abaengine-prod-proj).
Review tabs for Storage, Networking, and Identity (ensure System-assigned Managed Identity is enabled), then click Review + create followed by Create.
Step 2: Deploy DeepSeek-V4 via the Model Catalog
Once provisioning finishes, click Go to resource and launch the Foundry portal (ai.azure.com).
In the left navigation menu, click Catalog to open the Model Catalog.
Search for DeepSeek-V4 to view the available natively hosted variants (such as DeepSeek-V4-Pro, DeepSeek-V4-Flash, and DeepSeek-V4.1-Flash).
Select your preferred variant (e,g., DeepSeek-V4-Flash for high-throughput, cost-efficient workloads), click Deploy, and set your deployment name (e.g., DeepSeek-V4-Flash) and Tokens-per-Minute (TPM) rate limit.
Upon successful completion, your deployment appears under your project dashboard and is ready for inference.
Phase 2: Building the ASP.NET Core MVC Application
With the cloud endpoint active, we can build a modern ASP.NET Core MVC web application to interact with the DeepSeek-V4 model.
Step 1: Install Required NuGet Packages
In your Visual Studio NuGet Package Manager, ensure you have installed the official, non-deprecated packages:
Step 2: Configure appsettings.json
Add your Microsoft Foundry endpoint and deployment details to appsettings.json. Leave ApiKey blank if using keyless Microsoft Entra ID authentication (DefaultAzureCredential), or populate it if testing with an explicit API key:
JSON
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AzureAI": {
"Endpoint": "https://<YOUR-RESOURCE-NAME>.openai.azure.com/openai/v1/",
"DeploymentName": "DeepSeek-V4-Flash",
"ApiKey": ""
}
}
Phase 3: Core Implementation Code
1. Options Binding (Options/AzureAiOptions.cs)
C#
using System.ComponentModel.DataAnnotations;
namespace DeepSeekIntegration.Options;
public class AzureAiOptions
{
public const string SectionName = "AzureAI";
[Required, Url]
public required string Endpoint { get; init; }
[Required]
public required string DeploymentName { get; init; }
public string? ApiKey { get; init; }
}
2. Service Abstraction & Implementation (Services/DeepSeekService.cs)
C#
using DeepSeekIntegration.Options;
using Microsoft.Extensions.Options;
using OpenAI;
using OpenAI.Chat;
namespace DeepSeekIntegration.Services;
public interface IDeepSeekService
{
Task<(string Reply, int TotalTokens)> AskAsync(
string userPrompt,
string? systemPrompt = null,
CancellationToken cancellationToken = default);
}
public class DeepSeekService(
OpenAIClient openAiClient,
IOptions<AzureAiOptions> options) : IDeepSeekService
{
private readonly ChatClient _chatClient = openAiClient.GetChatClient(options.Value.DeploymentName);
public async Task<(string Reply, int TotalTokens)> AskAsync(
string userPrompt,
string? systemPrompt = null,
CancellationToken cancellationToken = default)
{
List<ChatMessage> messages = [];
if (!string.IsNullOrWhiteSpace(systemPrompt))
{
messages.Add(new SystemChatMessage(systemPrompt));
}
messages.Add(new UserChatMessage(userPrompt));
var completionOptions = new ChatCompletionOptions
{
MaxOutputTokenCount = 2048,
Temperature = 0.7f
};
ChatCompletion response = await _chatClient.CompleteChatAsync(
messages,
completionOptions,
cancellationToken);
string text = response.Content.FirstOrDefault()?.Text ?? string.Empty;
int totalTokens = response.Usage?.TotalTokenCount ?? 0;
return (text, totalTokens);
}
}
3. Application Startup (Program.cs)
Configure dependency injection, configuration binding, and enterprise authentication support supporting both API keys and managed identities via BearerTokenPolicy:
C#
using System.ClientModel;
using System.ClientModel.Primitives;
using Azure.Identity;
using DeepSeekIntegration.Options;
using DeepSeekIntegration.Services;
using Microsoft.Extensions.Options;
using OpenAI;
namespace DeepSeekIntegration;
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services
.AddOptions<AzureAiOptions>()
.BindConfiguration(AzureAiOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
#pragma warning disable OPENAI001
builder.Services.AddSingleton(sp =>
{
var settings = sp.GetRequiredService<IOptions<AzureAiOptions>>().Value;
var clientOptions = new OpenAIClientOptions
{
Endpoint = new Uri(settings.Endpoint)
};
if (!string.IsNullOrWhiteSpace(settings.ApiKey))
{
return new OpenAIClient(new ApiKeyCredential(settings.ApiKey), clientOptions);
}
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
return new OpenAIClient(authenticationPolicy: tokenPolicy, options: clientOptions);
});
#pragma warning restore OPENAI001
builder.Services.AddScoped<IDeepSeekService, DeepSeekService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapStaticAssets();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}")
.WithStaticAssets();
app.Run();
}
}
Phase 4: View Models, Controllers, and Accessible Views
1. View Model (Models/ChatViewModel.cs)
C#
using System.ComponentModel.DataAnnotations;
namespace DeepSeekIntegration.Models;
public class ChatViewModel
{
[Display(Name = "System Instructions (Optional)")]
public string SystemPrompt { get; set; } = "You are a helpful AI assistant.";
[Required(ErrorMessage = "Please enter a message before sending.")]
[Display(Name = "Your Prompt")]
public string UserPrompt { get; set; } = string.Empty;
public string? AssistantReply { get; set; }
public int? TotalTokensUsed { get; set; }
public long? ElapsedMilliseconds { get; set; }
public string? ErrorMessage { get; set; }
}
2. Controller (Controllers/HomeController.cs)
C#
using System.Diagnostics;
using DeepSeekIntegration.Models;
using DeepSeekIntegration.Services;
using Microsoft.AspNetCore.Mvc;
namespace DeepSeekIntegration.Controllers;
public class HomeController(
IDeepSeekService deepSeekService,
ILogger<HomeController> logger) : Controller
{
[HttpGet]
public IActionResult Index() => View(new ChatViewModel());
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ChatViewModel model, CancellationToken cancellationToken)
{
if (!ModelState.IsValid) return View(model);
var sw = Stopwatch.StartNew();
try
{
var (reply, totalTokens) = await deepSeekService.AskAsync(
model.UserPrompt, model.SystemPrompt, cancellationToken);
sw.Stop();
model.AssistantReply = reply;
model.TotalTokensUsed = totalTokens;
model.ElapsedMilliseconds = sw.ElapsedMilliseconds;
}
catch (Exception ex)
{
sw.Stop();
logger.LogError(ex, "Error calling DeepSeek-V4 endpoint.");
model.ErrorMessage = $"Request failed: {ex.Message}";
}
return View(model);
}
}
3. Razor View (Views/Home/Index.cshtml)
Note: Uses the accessible <output> element for loading indicators instead of standard status roles to ensure full device compatibility.
HTML
@model DeepSeekIntegration.Models.ChatViewModel
@{
ViewData["Title"] = "DeepSeek-V4 Playground";
}
<div class="container py-4" style="max-width: 860px;">
<div class="d-flex align-items-center justify-content-between mb-3">
<div>
<h2 class="mb-0">DeepSeek-V4 Assistant</h2>
<small class="text-muted">Connected to Microsoft Foundry</small>
</div>
<span class="badge bg-success">Azure Foundry v1</span>
</div>
@if (!string.IsNullOrWhiteSpace(Model.ErrorMessage))
{
<div class="alert alert-danger" role="alert">@Model.ErrorMessage</div>
}
<div class="card shadow-sm">
<div class="card-body">
<form asp-action="Index" method="post" id="chatForm">
@Html.AntiForgeryToken()
<div class="mb-3">
<label asp-for="SystemPrompt" class="form-label fw-semibold"></label>
<input asp-for="SystemPrompt" class="form-control form-control-sm" />
</div>
<div class="mb-3">
<label asp-for="UserPrompt" class="form-label fw-semibold"></label>
<textarea asp-for="UserPrompt" class="form-control" rows="4" placeholder="Ask DeepSeek-V4 anything..."></textarea>
<span asp-validation-for="UserPrompt" class="text-danger small"></span>
</div>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary px-4" id="submitBtn">
<span id="btnText">Send Prompt</span>
<output id="btnSpinner" class="spinner-border spinner-border-sm ms-2 d-none" aria-label="Loading"></output>
</button>
</div>
</form>
</div>
</div>
@if (!string.IsNullOrWhiteSpace(Model.AssistantReply))
{
<div class="card shadow-sm mt-4 border-primary">
<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
<span class="fw-semibold">DeepSeek-V4 Response</span>
<small>
@Model.ElapsedMilliseconds ms
@if (Model.TotalTokensUsed is > 0)
{
<span> • @Model.TotalTokensUsed tokens</span>
}
</small>
</div>
<div class="card-body bg-light">
<pre class="mb-0" style="white-space: pre-wrap; font-family: inherit;">@Model.AssistantReply</pre>
</div>
</div>
}
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
<script>
document.getElementById('chatForm').addEventListener('submit', function () {
if ($(this).valid()) {
document.getElementById('submitBtn').disabled = true;
document.getElementById('btnText').textContent = 'Generating...';
document.getElementById('btnSpinner').classList.remove('d-none');
}
});
</script>
}
Conclusion
By following this architecture, you have successfully established an enterprise-grade AI integration pipeline: your model runs securely on Microsoft Foundry, and your ASP.NET Core MVC application consumes it cleanly, utilising modern dependency injection, robust error handling, and secure authentication.
You can find the complete, production-ready source code and implementation examples in the accompanying DeepSeekWithDoteNetCoreApp GitHub Repository.
Join the conversation! Your thoughts help the community grow.