---
title: "Expose the Ollama API via a Public API Implementation in .NET Core"  
description: "Ollama enables developers to run Large Language Models (LLMs) locally. However, many real-world applications require external access to these models through a p"  
author: "Anubhav Sharma"  
published: 2026-06-09  
updated: 2026-06-10  
canonical: https://answers.mindstick.com/blog/384/expose-the-ollama-api-via-a-public-api-implementation-in-dot-net-core  
category: "programming"  
tags: ["ollama", "programming language", "artificial intelligence"]  
reading_time: 4 minutes  

---

# Expose the Ollama API via a Public API Implementation in .NET Core

[Ollama](https://answers.mindstick.com/blog/350/understanding-ollama-api) enables developers to run [Large Language Models (LLMs)](https://www.mindstick.com/interview/34471/what-is-a-large-language-model-llm) locally. However, many real-world applications require external access to these models through a public API.

![Expose the Ollama API via a Public API Implementation in .NET Core](https://answers.mindstick.com/blogs/8995c16a-47f5-429a-ae6b-45e514a0fcb1/images/3534b131-768e-4143-8952-c85549099ad8.png)

## Prerequisites

Before starting, ensure that:

- .NET 8 SDK is installed.
- Ollama is installed and running.
- At least one model is downloaded.

Check available models:

```plaintext
ollama list
```

Example:

```plaintext
llama3.2
mistral
gemma3
deepseek-r1
```

Start Ollama:

```plaintext
ollama serve
```

By default, Ollama runs on:

```plaintext
http://localhost:11434
```

## Step 1: Create a .NET Core Web API

Create a new project:

```plaintext
dotnet new webapi -n OllamaPublicApi
cd OllamaPublicApi
```

Run the project:

```plaintext
dotnet run
```

## Step 2: Create Request Models

Create a folder named **Models**.

### Models/ChatRequest.cs

```cs
namespace OllamaPublicApi.Models
{
    public class ChatRequest
    {
        // AI model name
        public string Model { get; set; }

        // User prompt
        public string Prompt { get; set; }
    }
}
```

## Step 3: Register HttpClient

Open **Program.cs**.

```cs
// Create builder
var builder = WebApplication.CreateBuilder(args);

// Register controllers
builder.Services.AddControllers();

// Register HttpClient for API calls
builder.Services.AddHttpClient();

// Enable Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Enable Swagger UI
app.UseSwagger();
app.UseSwaggerUI();

// Map controllers
app.MapControllers();

// Run application
app.Run();
```

## Step 4: Create Ollama Controller

Create a folder named **Controllers**.

### Controllers/OllamaController.cs

```cs
using Microsoft.AspNetCore.Mvc;
using OllamaPublicApi.Models;
using System.Text;
using System.Text.Json;

namespace OllamaPublicApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OllamaController : ControllerBase
    {
        // HttpClient factory instance
        private readonly IHttpClientFactory _httpClientFactory;

        // Constructor injection
        public OllamaController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

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

            // Build Ollama request payload
            var payload = new
            {
                model = request.Model,
                prompt = request.Prompt,
                stream = false
            };

            // Convert object into JSON string
            var json = JsonSerializer.Serialize(payload);

            // Create HTTP content
            var content = new StringContent(
                json,
                Encoding.UTF8,
                "application/json");

            // Send request to Ollama API
            var response = await client.PostAsync(
                "http://localhost:11434/api/generate",
                content);

            // Read response body
            var result = await response.Content.ReadAsStringAsync();

            // Return response to client
            return Content(result, "application/json");
        }
    }
}
```

## Step 5: Test Dynamic Model Selection

### Request Using Llama

```plaintext
POST /api/ollama/chat
```

```plaintext
{
  "model": "llama3.2",
  "prompt": "Explain machine learning."
}
```

### Request Using Mistral

```plaintext
{
  "model": "mistral",
  "prompt": "Explain machine learning."
}
```

### Request Using DeepSeek

```plaintext
{
  "model": "deepseek-r1",
  "prompt": "Explain machine learning."
}
```

The API automatically forwards the selected model to Ollama.

## Step 6: Create Model Listing Endpoint

Allow clients to discover available models.

Add the following method inside **OllamaController**.

```cs
[HttpGet("models")]
public async Task<IActionResult> GetModels()
{
    // Create HttpClient
    var client = _httpClientFactory.CreateClient();

    // Call Ollama tags endpoint
    var response = await client.GetAsync(
        "http://localhost:11434/api/tags");

    // Read response
    var result = await response.Content.ReadAsStringAsync();

    // Return model list
    return Content(result, "application/json");
}
```

Test:

```plaintext
GET /api/ollama/models
```

Example Response:

```plaintext
{
  "models": [
    {
      "name": "llama3.2"
    },
    {
      "name": "mistral"
    }
  ]
}
```

## Step 7: Add API Key Security

Add the following code to the Chat method.

```cs
// Read API Key from request header
var apiKey = Request.Headers["X-API-KEY"].ToString();

// Validate API Key
if (apiKey != "my-secret-key")
{
    // Return unauthorized response
    return Unauthorized("Invalid API Key");
}
```

Client Request:

```plaintext
POST /api/ollama/chat
```

Headers:

```plaintext
X-API-KEY: my-secret-key
```

This prevents unauthorized access.

## Step 8: Expose API Publicly

## Option 1: Ngrok

Install Ngrok and run:

```plaintext
ngrok http 5000
```

Example:

```plaintext
https://abc123.ngrok-free.app
```

Public Endpoint:

```plaintext
https://abc123.ngrok-free.app/api/ollama/chat
```

## Option 2: Deploy to Cloud

Deploy your [application](https://www.mindstick.com/blog/59/xaml-extensible-application-markup-language) to:

- [AWS EC2](https://aws.amazon.com/ec2/customers/)
- Azure Virtual Machine
- [Google Cloud VM](https://cloud.google.com/learn/what-is-a-virtual-machine)
- DigitalOcean

Install Ollama on the server:

```plaintext
ollama serve
```

Publish the .NET application:

```plaintext
dotnet publish -c Release
```

Run:

```plaintext
dotnet OllamaPublicApi.dll
```

Configure firewall and reverse proxy settings.

## Recommended Models

| Model | Purpose |
| --- | --- |
| llama3.2 | General AI assistant |
| mistral | Fast responses |
| gemma3 | Lightweight applications |
| deepseek-r1 | Reasoning and coding |
| qwen3 | Multilingual tasks |
| codellama | Code generation |

## Conclusion

Using [ASP.NET Core and Ollama](https://answers.mindstick.com/blog/375/building-an-enterprise-ai-search-engine-with-ollama), you can quickly build a secure public AI API. The [implementation](https://www.mindstick.com/interview/733/what-is-implementation-and-interface-inheritance) allows clients to dynamically choose models, making it suitable for chatbots, AI assistants, content generation platforms, and [enterprise AI solutions](https://www.mindstick.com/articles/337935/what-is-amazon-q-developer-ai-chatbot-for-companies). By adding model discovery, API key [authentication](https://www.mindstick.com/blog/177/authentication-and-authorization-in-asp-dot-net), and public [deployment](https://www.mindstick.com/articles/332756/exploring-the-benefits-of-continuous-integration-and-deployment), you can create a production-ready AI service powered by locally hosted LLMs.

---

Original Source: https://answers.mindstick.com/blog/384/expose-the-ollama-api-via-a-public-api-implementation-in-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
