DOTNET EXPERT BLOG

Build Your First AI Application with C# and .NET: Day 1

9/26/2026 5:00:51 AM Noor All Safaet Loading... 0

Build Your First AI Application with C# and .NET: Day 1

Artificial intelligence is becoming part of everyday software development.

But if you are a C# developer, you don't need to leave the .NET ecosystem to start building AI-powered applications.

You can use familiar .NET concepts such as C#, dependency injection, configuration, services, APIs, and asynchronous programming while connecting your application to modern AI models.

This tutorial series takes a practical approach.

Instead of explaining AI concepts for dozens of pages before writing any code, we are going to build an AI application step by step.

Each day will add another capability to the same project.

By the end of the series, the simple application we start today will evolve into a much more capable AI-powered .NET application with features such as conversation memory, structured responses, tool calling, RAG, and agent-style workflows.

Today is Day 1.

Our goal is simple:

Create a C# application, connect it to an AI model, send a prompt, and receive the model's response.

What We Are Building

Before writing code, it is useful to understand where this series is going.

We will gradually build an AI-powered business assistant using C# and .NET.

The final application will be able to work with business information and perform useful tasks rather than simply returning text.

The learning path will look roughly like this:

Day 1
Basic AI request
      ↓
Day 2
AI service abstraction
      ↓
Day 3
Reusable chat service
      ↓
Day 4
Conversation memory
      ↓
Day 5
Streaming responses
      ↓
Day 6
Structured output
      ↓
Day 7
C# function calling
      ↓
Day 8
AI + database
      ↓
Day 9
RAG
      ↓
Day 10
AI agent
      ↓
Production features

We will not build everything today.

The purpose of Day 1 is to establish a clean foundation.

Why Build AI Applications with C#?

If you already develop applications with .NET, there is no reason to learn an entirely different application stack just to add AI features.

.NET provides libraries and abstractions for connecting applications to modern AI services.

Microsoft's current .NET AI ecosystem includes support for providers such as OpenAI, Azure OpenAI, Azure AI Foundry, Ollama, Google Gemini, and Amazon Bedrock. The Microsoft.Extensions.AI abstractions provide a common programming model for application developers.

That means your application architecture can remain familiar:

C#
 ↓
.NET
 ↓
Service Layer
 ↓
AI Abstraction
 ↓
AI Provider
 ↓
AI Model

You can still use:

  • Dependency injection

  • Configuration

  • Interfaces

  • Services

  • Logging

  • Async/await

  • ASP.NET Core

  • Entity Framework Core

  • PostgreSQL

  • SQL Server

The AI becomes another capability inside your application rather than a completely separate technology stack.

What Is Microsoft.Extensions.AI?

For this series, one important component is:

Microsoft.Extensions.AI

It provides common abstractions for working with AI services in .NET.

One of the most important abstractions is:

IChatClient

IChatClient represents a client that can communicate with AI services capable of chat-style interactions.

The advantage is that your application code can work against the abstraction instead of being tightly coupled to one provider-specific client API.

Conceptually:

Your C# Application
        ↓
    IChatClient
        ↓
 AI Provider Client
        ↓
    AI Model

This separation will become more useful as our project becomes more advanced.

Prerequisites

Before starting, make sure your development environment is ready.

You should have:

  • Basic knowledge of C#

  • Familiarity with the .NET CLI

  • .NET 8 SDK or later

  • Visual Studio, Visual Studio Code, or another C# editor

  • An account with an AI provider

  • An API key or another supported authentication method

  • Basic understanding of asynchronous C# code

You don't need to know machine learning to follow this tutorial.

You also don't need:

  • Python

  • TensorFlow

  • PyTorch

  • A GPU

  • A machine-learning background

We are building an application that consumes an AI model rather than training an AI model ourselves.

For this first tutorial, we will use an OpenAI-compatible integration. The same overall architecture will be useful when we explore other providers later.

What You Need Before Starting

You need:

  • .NET 8 SDK or later

  • Visual Studio, Visual Studio Code, or another C# editor

  • An AI provider account

  • An API key or another supported authentication method

Microsoft's current .NET AI quickstart supports .NET 8 or later and demonstrates connecting a .NET application to OpenAI or Azure OpenAI.

For this first tutorial, we will use an OpenAI-compatible integration because it keeps the initial example straightforward.

The same IChatClient abstraction can also be used with other supported providers.

Step 1: Create a C# Project

Open a terminal and create a new console application:

dotnet new console -n CSharpAiTutorial

Move into the project:

cd CSharpAiTutorial

You should now have a basic .NET project:

CSharpAiTutorial/
│
├── CSharpAiTutorial.csproj
├── Program.cs
└── obj/

At this point, this is just a normal C# application.

There is nothing AI-specific yet.

That is intentional.

Step 2: Add the Required Packages

Install the Microsoft AI abstractions and OpenAI integration:

dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
dotnet add package OpenAI

Microsoft's current quickstart uses Microsoft.Extensions.AI.OpenAI together with the OpenAI package to expose an OpenAI client through IChatClient.

The exact package version and prerelease status can change over time, so always check the current package information when creating a new project.

Step 3: Never Hard-Code Your API Key

One of the most important habits to establish from Day 1 is:

Do not put your API key directly inside Program.cs.

Avoid code like this:

var apiKey = "sk-your-secret-key";

Why?

Because the key can accidentally end up in:

  • Git repositories

  • GitHub

  • Screenshots

  • Logs

  • Deployment artifacts

  • Shared code

Instead, use .NET configuration and User Secrets during local development.

Initialize User Secrets:

dotnet user-secrets init

Then store your API key:

dotnet user-secrets set OpenAIKey "YOUR_API_KEY"

You can also store the model name:

dotnet user-secrets set ModelName "YOUR_MODEL_NAME"

Replace the placeholder with the model you actually have access to.

Microsoft's current .NET AI quickstart also demonstrates using User Secrets to keep the OpenAI key and model configuration outside the source code.

Step 4: Read the Configuration

Now open Program.cs.

We can load the User Secrets configuration:

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder()
    .AddUserSecrets<Program>()
    .Build();

string? apiKey = config["OpenAIKey"];
string? model = config["ModelName"];

At this point:

OpenAIKey
    ↓
Configuration

ModelName
    ↓
Configuration

The application does not need to know where the values are stored.

That becomes useful later when we move from local development to production.

Step 5: Create an IChatClient

Now we can connect the OpenAI client to the .NET AI abstraction.

Add:

using Microsoft.Extensions.AI;
using OpenAI;

Then:

IChatClient chatClient =
    new OpenAIClient(apiKey)
        .GetChatClient(model)
        .AsIChatClient();

The important part here is not just the OpenAI client.

It is this:

IChatClient

Our application now depends on an abstraction rather than directly depending on the provider-specific chat client.

Step 6: Send Your First AI Prompt

Now we can finally ask the model something.

The simplest version is:

var response = await chatClient.GetResponseAsync(
    "Explain dependency injection in C# in simple terms.");

Console.WriteLine(response);

That's our first AI-powered C# application.

The complete Program.cs can look like this:

using Microsoft.Extensions.AI;
using Microsoft.Extensions.Configuration;
using OpenAI;

var config = new ConfigurationBuilder()
    .AddUserSecrets<Program>()
    .Build();

string? apiKey = config["OpenAIKey"];
string? model = config["ModelName"];

if (string.IsNullOrWhiteSpace(apiKey))
{
    Console.WriteLine("OpenAI API key is missing.");
    return;
}

if (string.IsNullOrWhiteSpace(model))
{
    Console.WriteLine("AI model name is missing.");
    return;
}

IChatClient chatClient =
    new OpenAIClient(apiKey)
        .GetChatClient(model)
        .AsIChatClient();

var response = await chatClient.GetResponseAsync(
    "Explain dependency injection in C# in simple terms.");

Console.WriteLine();
Console.WriteLine(response);

Run the application:

dotnet run

The model should return a response explaining dependency injection.

You have now built your first AI application with C#.

What Just Happened?

It may look like only a few lines of code, but several things happened behind the scenes.

Your Prompt
     ↓
IChatClient
     ↓
OpenAI Client
     ↓
AI API
     ↓
AI Model
     ↓
Generated Response
     ↓
Your C# Application

Your application sends the prompt to the AI service.

The AI service processes the request using the selected model.

The generated response comes back to your application.

Your application then writes the response to the console.

This basic request-response pattern is the foundation for almost everything we will build later.

Understanding GetResponseAsync

The key method is:

GetResponseAsync()

For example:

var response = await chatClient.GetResponseAsync(
    "What is ASP.NET Core?");

The method sends a request to the configured AI service and returns a ChatResponse.

You can also provide additional options.

For example:

var response = await chatClient.GetResponseAsync(
    "Explain REST API in simple terms.",
    new ChatOptions
    {
        MaxOutputTokens = 300
    });

We will explore ChatOptions more deeply in a later article.

Adding a System Instruction

An AI model can receive more than a single user prompt.

We can provide system-level instructions that describe the role or behavior we want.

For example:

var messages = new List<ChatMessage>
{
    new(ChatRole.System,
        "You are a helpful C# programming assistant."),

    new(ChatRole.User,
        "Explain async and await in C#.")
};

var response = await chatClient.GetResponseAsync(messages);

Console.WriteLine(response);

Now the interaction has two parts:

System
"You are a helpful C# programming assistant."

        +

User
"Explain async and await in C#."

This pattern becomes important when we build a reusable AI service.

Why We Are Not Building an ASP.NET Core API Yet

You may be wondering:

Why are we starting with a console application instead of ASP.NET Core?

Because Day 1 is about understanding the smallest working AI integration.

We don't need:

  • Controller

  • HTTP endpoint

  • Database

  • Authentication

  • UI

  • JavaScript

to make our first AI request.

Starting small makes it easier to understand the underlying AI integration.

Later, we will move the same concept into ASP.NET Core.

The architecture will then become:

Browser
   ↓
ASP.NET Core API
   ↓
AI Service
   ↓
IChatClient
   ↓
AI Model

Provider Abstraction Is Important

One reason to learn IChatClient early is that AI providers can change.

Today you might use:

OpenAI

Tomorrow you might use:

Azure OpenAI

Or perhaps:

Ollama

for a local model.

Microsoft's .NET AI ecosystem supports multiple providers through common abstractions, which can reduce the amount of application code tied directly to a particular provider.

This doesn't mean switching providers is always a one-line change.

Models have different capabilities, pricing, context limits, authentication methods, and behavior.

But keeping your application code dependent on abstractions gives you a cleaner architecture.

A Better Project Structure

For today's console application, Program.cs is enough.

But as the series grows, putting everything into one file would quickly become difficult to maintain.

We can eventually move toward:

CSharpAiTutorial/
│
├── Program.cs
│
├── Configuration/
│   └── AiOptions.cs
│
├── Services/
│   └── AiChatService.cs
│
├── Models/
│   └── ChatRequest.cs
│
└── Extensions/
    └── ServiceCollectionExtensions.cs

We don't need to create all of these files today.

The architecture will evolve as the application becomes more capable.

Common Errors and How to Fix Them

Your first AI request may not work on the first attempt.

That's normal.

Here are some common problems you may encounter.

1. API Key Is Missing

You may see:

OpenAI API key is missing.

Check whether the User Secret exists:

dotnet user-secrets list

You should see your configured key name.

If it is missing, set it again:

dotnet user-secrets set OpenAIKey "YOUR_API_KEY"

Also make sure you are running the command from the correct project directory.

2. Model Name Is Missing

If you see:

AI model name is missing.

configure the model:

dotnet user-secrets set ModelName "YOUR_MODEL_NAME"

Use a model that is available to your account and compatible with the API you are using.

3. Invalid API Key

If the request reaches the provider but authentication fails, check:

  • The API key is correct.

  • The key has not been revoked.

  • The application is using the expected account/project.

  • The key has the required permissions.

  • You did not accidentally include extra spaces.

Don't paste the secret key into your source code just to test it.

4. Model Not Found

A model name that worked in an older tutorial may not necessarily be available to your account or provider configuration.

If you receive a model-related error:

  1. Check the provider's current model list.

  2. Confirm that the model name is spelled correctly.

  3. Verify that your account has access to it.

  4. Update your User Secret.

For example:

dotnet user-secrets set ModelName "YOUR_MODEL_NAME"

5. Package Installation Problems

If this command fails:

dotnet add package Microsoft.Extensions.AI.OpenAI

check the current package availability and compatible version.

You can inspect available packages with:

dotnet list package

If you're following an older tutorial, don't blindly copy package versions from it.

.NET AI libraries are evolving quickly, so the package version shown in an older article may no longer match the current ecosystem.

6. IChatClient or Extension Method Is Not Found

If the compiler doesn't recognize:

IChatClient

make sure the appropriate namespace is imported:

using Microsoft.Extensions.AI;

If:

.AsIChatClient()

is not recognized, check that the corresponding Microsoft.Extensions.AI provider integration package is installed and compatible with the other package versions in your project.

Then run:

dotnet restore

and rebuild the project:

dotnet build

7. Rate Limit or Quota Error

Your code can be correct and the request can still fail because of provider-side limits.

Possible causes include:

  • Request rate limits

  • Account quota

  • Usage limits

  • Temporary service restrictions

In that situation, inspect the provider's response and account usage rather than changing the C# code unnecessarily.

Later in this series, we will discuss retry policies and resilient AI calls.

Don't Send Sensitive Information to an AI Model

This is another habit worth establishing from the first day.

If your application contains:

  • Passwords

  • API keys

  • Access tokens

  • Private customer information

  • Financial information

  • Internal credentials

do not simply put them into an AI prompt.

For example, avoid:

var prompt = $"""
Here is the customer's complete database record:

{customerRecord}

Summarize it.
""";

without considering what information is actually necessary.

A production AI application needs data minimization, access control, appropriate provider configuration, and a clear understanding of what information is being sent to the model.

Security will become an important part of this series.

What We Have Built So Far

At the end of Day 1, our application is intentionally simple.

C# Console Application
        ↓
Configuration
        ↓
IChatClient
        ↓
OpenAI
        ↓
AI Model
        ↓
Response

That's it.

But this small application is the foundation for the rest of the series.

What Comes Next?

Today we directly created an IChatClient inside Program.cs.

That works for a small example.

It isn't the architecture we want for a growing application.

Tomorrow we will improve it.

Day 2: Calling AI Models from C# with Microsoft.Extensions.AI

We will move the AI integration into a cleaner application structure and learn:

  • IChatClient

  • Dependency injection

  • AI service registration

  • Configuration

  • Provider abstraction

  • Reusable AI services

The code we write tomorrow will build directly on today's project.

Day 1 Checklist

Before moving to Day 2, make sure you can:

  • Create a .NET console application

  • Install the required AI packages

  • Configure User Secrets

  • Store your AI API key securely

  • Configure the model name

  • Create an IChatClient

  • Send a prompt

  • Receive an AI response

  • Understand the basic AI request flow

  • Explain why application code should use abstractions

  • Diagnose common API key and model configuration problems

If all of these are working, your first C# AI application is ready.

Final Thoughts

You don't need to become a machine-learning researcher before you can build AI applications.

If you already know C#, you can start from familiar .NET concepts and gradually add AI capabilities to your applications.

The important thing is to start with a small, understandable integration.

Today we created a C# application that connects to an AI model and receives a response using IChatClient.

That may look simple, but it gives us the foundation for everything that comes next.

We will now build on the same project rather than creating disconnected examples.

The goal is not to learn AI through isolated code snippets.

The goal is to build a real AI-powered .NET application one step at a time.

This is Day 1. The next step is turning this first AI request into a reusable .NET service.

Comments 0