We put excellence, value and quality above all - and it shows
A Technology Partnership That Goes Beyond Code
“Arbisoft has been my most trusted technology partner for now over 15 years. Arbisoft has very unique methods of recruiting and training, and the results demonstrate that. They have great teams, great positive attitudes and great communication.”
Building Robust APIs with .NET Core and C#: A Comprehensive Guide

APIs (Application Programming Interfaces) form the backbone of scalable, maintainable, and reusable software services. This comprehensive guide demonstrates how to build robust and modular APIs using .NET Core and C#. We'll cover everything from setting up your first project to integrating Entity Framework Core, LINQ, and preparing for real-world development with extensible and secure design.
Why .NET Core for APIs?
.NET Core (now just .NET from version 6 onwards) is an open-source, cross-platform framework designed by Microsoft. Its fast performance, strong type system, built-in dependency injection, and robust tooling make it ideal for enterprise-grade backend development.
This guide will not only show you how to build APIs, but how to build them right — using best practices for structure, maintainability, and extendibility.
Prerequisites
Before diving in, make sure you have the following tools installed on your system:
Tool | Mac | Windows |
.NET SDK (6+) | https://dotnet.microsoft.com/download | https://dotnet.microsoft.com/download |
IDE/Editor | VS Code | Visual Studio 2022+ |
API Testing | Postman or any browser | Postman or browser |
DB Tool (Optional) | Azure Data Studio / DBeaver / Postgres | SSMS / Azure Data Studio |
Step 1: Create a New Web API Project
Option A: Command Line (Mac & Windows)
dotnet new webapi -n MyFirstApi
cd MyFirstApi
code .
Option B: Visual Studio
- Open Visual Studio
- Click Create a new project
- Choose ASP.NET Core Web API
- Name it MyFirstApi, select .NET 6+, then Create
Initial Project Structure (Default Minimal API)
Step 2: Enable Controller-Based Structure
Generated Program.cs
To move away from minimal APIs and use traditional controllers like HelloController:
Update Program.cs
Removed Default /weatherforecast Endpoint
Delete this from the original Program.cs:
app.MapGet("/weatherforecast", () => { ... });
Replace everything in Program.cs with:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Now your app will only use controller-based routes.
Step 3: Add HelloController
Create Folder and File
mkdir Controllers
Create a file named Controllers/HelloController.cs and paste:
using Microsoft.AspNetCore.Mvc;
namespace MyFirstApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloController : ControllerBase
{
[HttpGet]
public string SayHello() => "Hello from .NET API!";
}
}
Now run:
dotnet build
dotnet run
Test at:
https://localhost:{port}/hello
Step 4: Return JSON Data
Update your controller:
[HttpGet("user")]
public IActionResult GetUser()
{
var user = new { Id = 1, Name = "John Doe" };
return Ok(user);
}
Then go to:
https://localhost:{port}/hello/user
Step 5: Integrate Entity Framework Core
Why Use Entity Framework Core?
Entity Framework Core (EF Core) is an Object-Relational Mapper (ORM) that simplifies database access in your .NET applications. Instead of writing raw SQL, you work with C# classes and LINQ to query and manipulate your data.
EF Core helps you:
- Eliminate boilerplate SQL code with strongly-typed C# operations
- Maintain a clean domain model using classes that reflect your business logic
- Apply database migrations easily with version control support
- Improve developer productivity with IntelliSense and compile-time checks
With EF Core, your API logic becomes more maintainable, secure, and testable by abstracting direct database access.
Install EF Core Packages
dotnet add package Microsoft.EntityFrameworkCore
Choose SQL provider or Npgsql:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # For SQL Server
# or use Npgsql or Sqlite if needed
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
Also add the tooling:
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.EntityFrameworkCore.Design
Create Folders and Files
Add User Model
Added [Table("users")] because of case sensitive database (postgres)
using System.ComponentModel.DataAnnotations.Schema;
namespace MyFirstApi.Models
{
[Table("users")]
public class User
{
public int id { get; set; }
public string username { get; set; }
}
}
Create AppDbContext
using Microsoft.EntityFrameworkCore;
using MyFirstApi.Models;
namespace MyFirstApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; } = default!;
}
}
Register in Program.cs
For SQLServer
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
For Postgres etc.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(configuration.GetConnectionString("DefaultConnection")));
Add Connection String
In appsettings.json, (using Npgsql):
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5433;Database=dotnet_db;Username=postgres;Password=postgres"
}
Step 6: Create DB via Migrations
dotnet ef migrations add InitialCreate
dotnet ef database update
EF Core will create the database and the users table.
Step 7: Query the Data with LINQ
Now that you have EF Core set up, you can use LINQ (Language Integrated Query) to retrieve and filter data easily.
Example: Get All Users from the Database
Update HelloController.cs to inject AppDbContext:
using Microsoft.AspNetCore.Mvc;
using MyFirstApi.Data;
using MyFirstApi.Models;
namespace MyFirstApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class HelloController : ControllerBase
{
private readonly AppDbContext _context;
public HelloController(AppDbContext context)
{
_context = context;
}
[HttpGet("all-users")]
public ActionResult<IEnumerable<User>> GetAllUsers()
{
var users = _context.Users.ToList();
return Ok(users);
}
}
}
http://localhost:{port}/hello/all-users
[HttpGet("search")]
public IActionResult Search(string name)
{
var matched = _context.Users
.Where(u => u.username.Contains(name))
.ToList();
return Ok(matched);
}
- LINQ makes querying the database intuitive and type-safe using familiar C# syntax.
Then go to:
http://localhost:{port}/hello/search?name=khurram

Final Project Structure
What's Next for Real-World Robustness
- Add DTOs & Automapper: Decouple models from API contracts.
- Validation: Add FluentValidation for input safety.
- Custom Middleware: Handle global errors and response wrapping.
- Logging: Integrate Serilog or NLog.
- Security: Implement JWT Bearer Authentication.
- API Versioning: Use Microsoft.AspNetCore.Mvc.Versioning.
- Testing: Add unit tests (xUnit) and integration tests.
- Docker: Containerize your app for deployment.
- CI/CD: Use GitHub Actions or Azure Pipelines.
Final Recap
Task | Status |
Created .NET Web API Project | Done |
Switched to Controller-based Routing | Done |
Added HelloController + JSON Output | Done |
Integrated EF Core | Done |
Queried data using LINQ | Done |
Added roadmap for scalability | Done |
Summary
You now have a working, structured .NET Core API, with EF Core and LINQ integrated, ready to be expanded into a secure, scalable, and testable real-world backend service.
...Loading Related Blogs