arbisoft brand logo
arbisoft brand logo
Contact Us

Building Robust APIs with .NET Core and C#: A Comprehensive Guide

Khurram's profile picture
Khurram MehmoodPosted on
9-10 Min Read Time

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/downloadhttps://dotnet.microsoft.com/download
IDE/EditorVS CodeVisual Studio 2022+
API TestingPostman or any browserPostman or browser
DB Tool (Optional)Azure Data Studio / DBeaver / PostgresSSMS / 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 .

 

image illustrating code

 

Option B: Visual Studio

  1. Open Visual Studio
  2. Click Create a new project
  3. Choose ASP.NET Core Web API
  4. Name it MyFirstApi, select .NET 6+, then Create
     

Initial Project Structure (Default Minimal API)

unnamed.png

Step 2: Enable Controller-Based Structure

Generated Program.cs

Code Image

 

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.

 

unnamed (2).png

 

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!";
    }
}

 

code image 2

 

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

 

unnamed (4).png

 

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

unnamed (5).png

 

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"
  }

 

unnamed (6).png

 

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);
        }
    }
}

 

unnamed (7).png

 

http://localhost:{port}/hello/all-users

 

unnamed (9).png

 

[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

 

unnamed (13).png

 

Final Project Structure

unnamed (8).png
 

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

Explore More

Have Questions? Let's Talk.

We have got the answers to your questions.