How to Integrate DeepSeek AI in ASP.NET Core Web API (Step-by-Step Guide)

Vivek Jaiswal
92
{{e.like}}
{{e.dislike}}
1 days

Introduction

If you’re a .NET developer exploring AI, this guide is for you. In this tutorial, you’ll learn how to integrate DeepSeek AI into an ASP.NET Core Web API using the OpenRouter API.

By the end, you’ll be able to send prompts (like “Write a C# Hello World program”) and get intelligent AI-powered responses directly from your backend.

This is perfect for building:

  • AI-powered chatbots

  • Intelligent coding assistants

  • Natural language processing apps


๐Ÿš€ Why Use DeepSeek with OpenRouter?

  • Free testing key available via OpenRouter (great for experimenting).

  • Multiple models support, including deepseek/deepseek-chat.

  • Seamless integration with .NET using HttpClientFactory.

  • Clean & secure configuration via appsettings.json.


๐Ÿ“‚ Project Setup

We’ll create a simple ASP.NET Core Web API project that communicates with DeepSeek via OpenRouter.


1๏ธโƒฃ Add Configuration in appsettings.json

 
{
  "OpenRouter": {
    "ApiKey": "Your-Key"
  }
}

Replace "Your-Key" with your OpenRouter API key. (You can start with a free key for testing.)


2๏ธโƒฃ Configure HttpClient in Program.cs

 
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

var builder = WebApplication.CreateBuilder(args);

// Register HttpClient for OpenRouter
builder.Services.AddHttpClient("OpenRouter", client =>
{
    client.BaseAddress = new Uri("https://openrouter.ai/api/v1/");
    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {builder.Configuration["OpenRouter:ApiKey"]}");
    client.DefaultRequestHeaders.Add("HTTP-Referer", "http://localhost");
    client.DefaultRequestHeaders.Add("X-Title", "OpenRouter .NET Test");
    client.DefaultRequestHeaders.Add("Accept", "application/json");
});

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.MapControllers();
app.Run();

Here we registered an HttpClient named OpenRouter that automatically adds headers for every request.


3๏ธโƒฃ Create ChatController.cs

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace OpenRouterAspNetCore.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ChatController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public ChatController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public class ChatRequest
        {
            public string Prompt { get; set; }
        }

        [HttpPost("chat")]
        public async Task<IActionResult> Chat([FromBody] ChatRequest request)
        {
            var client = _httpClientFactory.CreateClient("OpenRouter");

            var body = new
            {
                model = "deepseek/deepseek-chat",
                messages = new[] {
                    new { role = "user", content = request.Prompt }
                }
            };

            var response = await client.PostAsync("chat/completions",
                new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"));

            var result = await response.Content.ReadAsStringAsync();
            return Content(result, "application/json");
        }
    }
}

This controller exposes an endpoint:

  • POST /api/chat/chat

  • Accepts a JSON body like:

 
{ "prompt": "Write a C# Hello World program" }
  • Returns DeepSeek AI’s response.


๐Ÿงช Testing the API

  1. Run your project.

  2. Open Swagger (/swagger) or use Postman.

  3. Send a request to:

 
POST https://localhost:5001/api/chat/chat

With body:

 

{ "prompt": "Explain Dependency Injection in C#" }

โœ… You’ll get a JSON response from DeepSeek AI!


 

โ“ Frequently Asked Questions (FAQ)

๐Ÿ”น 1. Is DeepSeek AI free to use?

Yes, you can start with a free testing API key via OpenRouter.

๐Ÿ”น 2. Can I use DeepSeek AI for production apps?

Yes, but for production you should use a paid API key with higher rate limits.

๐Ÿ”น 3. What kind of apps can I build with DeepSeek AI?

  • Chatbots

  • Document summarizers

  • Code assistants

  • Question-answering systems

๐Ÿ”น 4. How is this different from OpenAI GPT integration?

DeepSeek works via OpenRouter API, just like OpenAI models, but it’s optimized for efficient responses and often more cost-effective.

 

๐ŸŽฏ Conclusion

In this tutorial, we integrated DeepSeek AI into an ASP.NET Core Web API using OpenRouter.

  • We set up appsettings.json for API keys.

  • Configured HttpClientFactory for secure API calls.

  • Built a ChatController to send prompts and receive AI responses.

Now you can extend this project by:

  • Saving chat history in a database.

  • Building a frontend (React/Angular/Blazor) to consume your API.

  • Using more advanced DeepSeek models for specialized tasks.


๐Ÿ”– Related Resources


๐Ÿ’ก Pro Tip: Start with the free API key for testing, and when moving to production, keep your API keys secure using User Secrets or Environment Variables.

{{e.like}}
{{e.dislike}}
Comments
Follow up comments
{{e.Name}}
{{e.Comments}}
{{e.days}}
Follow up comments
{{r.Name}}
{{r.Comments}}
{{r.days}}
Author19 Articles
Vivek Jaiswal
More Related Tutorials