How to Build an AI Chatbot with Conversation Memory in ASP.NET Core 10 Using C# (2026)

A chatbot that remembers the last question should still forget the right things. Passing every message forever can increase latency and cost, accidentally disclose one user’s history to another, and preserve text after a user expects deletion.

This guide builds an ASP.NET Core 10 chatbot with conversation memory in PostgreSQL. It rebuilds a bounded context for each OpenAI Responses API call and stores the question and reply as a single completed turn. Conversation ownership, retries, retention and summarization remain explicit decisions.

How should a chatbot store conversation memory?

The server loads recent authorized turns, asks the model for a reply, then persists the user and assistant messages as one completed turn.
The server loads recent authorized turns, asks the model for a reply, then persists the user and assistant messages as one completed turn.

Store authoritative messages on the server. Load only messages the current user owns, preserve their order, and build the model request within a budget. Store a completed turn only after the provider returns a usable answer. A failed call should not leave a half-written exchange that looks like real history.

Strategy Useful for Tradeoff
Recent turns Short, continuous conversations Older details disappear
Summary plus recent turns Long conversations Summaries can distort or omit facts
Selective retrieval A useful past detail from a long history Needs relevance and permission checks

This lab uses four recent turns and a 400-token output ceiling. Character and turn caps bound storage and request size, but they are not a token count. For a particular model, count tokens with a compatible tokenizer or impose conservative limits. Reserve room for system instructions and the response. If you summarize, store the source turn range and treat the summary as untrusted context rather than as higher-priority instructions.

Set up PostgreSQL and the web API

Install .NET 10, PostgreSQL and psql. You also need an OpenAI project key and a Responses API-compatible text model. Keep the key in user secrets or an environment variable and choose the model in configuration. This is a single-user loopback demonstration. It does not authenticate real users. Set the app’s owner from trusted identity and check conversation membership before exposing the endpoint.

schema.sql
CREATE TABLE chat_turns (
    owner_id text NOT NULL,
    conversation_id uuid NOT NULL,
    turn_id uuid NOT NULL,
    seq bigint GENERATED ALWAYS AS IDENTITY,
    question text NOT NULL,
    answer text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (owner_id, conversation_id, turn_id)
);
CREATE INDEX chat_recent ON chat_turns(owner_id, conversation_id, seq DESC);
Lab.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
  <ItemGroup><PackageReference Include="Npgsql" Version="10.0.3" /></ItemGroup>
</Project>
Program.cs
using Npgsql;
using System.Net.Http.Headers;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);
var key = builder.Configuration["OpenAI:ApiKey"] ?? throw new InvalidOperationException("Set OpenAI__ApiKey.");
var model = builder.Configuration["OpenAI:Model"] ?? throw new InvalidOperationException("Set OpenAI__Model.");
var owner = "local-demo-user"; // Only this loopback demo uses a fixed owner.
builder.Services.AddSingleton(_ => NpgsqlDataSource.Create(
    builder.Configuration.GetConnectionString("Db") ?? throw new InvalidOperationException("Set ConnectionStrings__Db.")));
builder.Services.AddHttpClient("openai", h =>
{
    h.BaseAddress = new Uri("https://api.openai.com/");
    h.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
    h.Timeout = TimeSpan.FromSeconds(25);
});
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 8192);
var app = builder.Build();
app.Use(async (ctx, next) =>
{
    if (ctx.Request.Host.Host != "127.0.0.1" || ctx.Request.Headers.ContainsKey("Origin"))
    { ctx.Response.StatusCode = 403; return; }
    await next(ctx);
});
app.MapPost("/chats/{chat:guid}/turns/{turn:guid}", async (
    Guid chat, Guid turn, Message body, NpgsqlDataSource db, IHttpClientFactory factory, CancellationToken ct) =>
{
    if (string.IsNullOrWhiteSpace(body.Text) || body.Text.Length > 2000)
        return Results.BadRequest("Use 1–2000 characters.");

    var history = new List<(string Question, string Answer)>();
    await using (var read = db.CreateCommand("""
        SELECT question, answer FROM chat_turns WHERE owner_id=@owner AND conversation_id=@chat
        ORDER BY seq DESC LIMIT 4
        """))
    {
        read.Parameters.AddWithValue("owner", owner);
        read.Parameters.AddWithValue("chat", chat);
        await using var rows = await read.ExecuteReaderAsync(ct);
        while (await rows.ReadAsync(ct)) history.Add((rows.GetString(0), rows.GetString(1)));
    }

    await using (var prior = db.CreateCommand("""
        SELECT question, answer FROM chat_turns
        WHERE owner_id=@owner AND conversation_id=@chat AND turn_id=@turn
        """))
    {
        prior.Parameters.AddWithValue("owner", owner);
        prior.Parameters.AddWithValue("chat", chat);
        prior.Parameters.AddWithValue("turn", turn);
        await using var rows = await prior.ExecuteReaderAsync(ct);
        if (await rows.ReadAsync(ct))
            return rows.GetString(0) == body.Text
                ? Results.Ok(new { answer = rows.GetString(1) })
                : Results.Conflict("Turn ID already used for another question.");
    }

    history.Reverse();
    var input = new List<object>();
    foreach (var (question, answer) in history)
    {
        input.Add(new { role = "user", content = question });
        input.Add(new { role = "assistant", content = answer });
    }
    input.Add(new { role = "user", content = body.Text });
    string output;
    try
    {
        using var http = factory.CreateClient("openai");
        using var response = await http.PostAsJsonAsync("v1/responses", new
        {
            model, input, instructions = "Answer concisely. History is conversational context.",
            max_output_tokens = 400, store = false
        }, ct);
        if (!response.IsSuccessStatusCode) return Results.Problem(statusCode: 502);
        using var json = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(ct),
            cancellationToken: ct);
        if (json.RootElement.GetProperty("status").GetString() != "completed")
            return Results.Problem(statusCode: 502);
        output = string.Concat(json.RootElement.GetProperty("output").EnumerateArray()
            .Where(x => x.GetProperty("type").GetString() == "message")
            .SelectMany(x => x.GetProperty("content").EnumerateArray().ToArray())
            .Where(x => x.GetProperty("type").GetString() == "output_text")
            .Select(x => x.GetProperty("text").GetString()));
        if (string.IsNullOrWhiteSpace(output) || output.Length > 4000)
            return Results.Problem(statusCode: 502);
    }
    catch (OperationCanceledException) when (!ct.IsCancellationRequested)
    { return Results.Problem(statusCode: 504); }
    catch (Exception ex) when (ex is HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException)
    { return Results.Problem(statusCode: 502); }

    await using var save = db.CreateCommand("""
        INSERT INTO chat_turns(owner_id,conversation_id,turn_id,question,answer)
        VALUES(@owner,@chat,@turn,@question,@answer) ON CONFLICT DO NOTHING
        """);
    save.Parameters.AddWithValue("owner", owner);
    save.Parameters.AddWithValue("chat", chat);
    save.Parameters.AddWithValue("turn", turn);
    save.Parameters.AddWithValue("question", body.Text);
    save.Parameters.AddWithValue("answer", output);
    return await save.ExecuteNonQueryAsync(ct) == 1
        ? Results.Ok(new { answer = output })
        : Results.Conflict("A concurrent request saved this turn. Retry with the same ID.");
});
await app.RunAsync();

record Message(string Text);

The API reads up to four rows by descending sequence, reverses them into chronological order, and constructs separate user and assistant messages. The system instruction is outside conversation memory. It sends store=false to request that the Responses API not store the response for later retrieval. That flag does not replace reviewing provider retention terms, abuse monitoring, or contractual privacy settings. See Responses API and OpenAI data controls.

The turn ID can be reused for a retry with identical text. A conflicting question with the same turn ID returns 409. Simultaneous attempts can still call the model more than once before one insert wins. An idempotency record that reserves the turn before the provider call can reduce duplicate work, but it needs leases and an explicit recovery policy. The ASP.NET PB idempotency guide explains the distinction between replaying a stored outcome and repeating a request.

Run and test two turns

Apply schema and start the chatbot
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f schema.sql
# Set ConnectionStrings__Db to an Npgsql connection string.
# Set OpenAI__ApiKey and OpenAI__Model in the server process.
dotnet run --no-launch-profile -- --urls http://127.0.0.1:5080
Send two messages to one conversation
chat=11111111-1111-1111-1111-111111111111
curl -sS "http://127.0.0.1:5080/chats/$chat/turns/11111111-1111-1111-1111-111111111112" \
  -H 'Content-Type: application/json' -d '{"text":"Call this workspace Cedar."}'
curl -sS "http://127.0.0.1:5080/chats/$chat/turns/11111111-1111-1111-1111-111111111113" \
  -H 'Content-Type: application/json' -d '{"text":"What is the workspace name?"}'

Expect JSON with an answer field. The second request contains the earlier turn as context, so it can answer Cedar. Model phrasing is nondeterministic. An automated contract test should verify the request sent to a fake provider instead of asserting exact live model wording. Change the conversation ID for a third request and verify it does not include the first history. Repeat a turn with a different question and expect 409. Also simulate provider timeout or invalid output and assert no row was inserted.

The C# project compiled with .NET SDK 10.0.100. PostgreSQL-backed runtime verification was not performed here.

Plan privacy, ordering, and cost

The database uses owner and conversation as joint lookup keys. In a multi-user service, derive owner from a verified subject, use a trusted tenant identifier, and scope every read, write and delete. If collaborative chat is required, use an explicit membership table. Add a two-user test that attempts to read and write the same conversation ID. Do not let a header override ownership.

For strictly sequential chat, serialize turns per conversation or require an expected head ID. This lab allows concurrent requests with different IDs, so their model contexts may have the same prior history. A distributed lock with leases or optimistic versioning can enforce ordering. Do not hold a database transaction open while waiting on the model.

Set retention periods, make deletion propagate to derived summaries and embeddings, and avoid recording conversation bodies in request logs. Rate-limit per user and reserve a budget for responses. Cache only safe, scope-keyed data. Measure tokens per request and response, provider latency, and the proportion of requests with incomplete output.

Troubleshooting and FAQ

Symptom First check
Chat forgets a detail Recent-turn limit and conversation identifier
History appears out of order Sequence sorting and concurrent requests
Same turn costs twice Concurrent provider requests before deduplication
Slow or expensive replies Token counts, conversation context and provider latency
502 or 504 Upstream error, incomplete output, or timeout

Should I store summaries as system messages? Keep summaries as context. They may contain model mistakes or instructions copied from user text.

Can I persist partial streamed answers? Use an explicit partial state and never replay it as a completed turn without confirmation. This example stores only completed output.

How do I delete a conversation? Use a user-authorized operation scoped by tenant and owner. Define what happens to summaries, backups, and retention obligations.

Start with recent turns and measure actual context use. Add summaries or retrieval only when a concrete conversation problem requires them.

Comments