Learn C# ยท 14/15

ASP.NET Core Web APIs

8 min read

Hello there, Code Traveler! ๐ŸŽ’ Welcome to the engine room of the internet.

So far, you might have written C# code that runs in a black console window. It calculates things, prints text, and then... closes. Thatโ€™s cool, but in the real world, software needs to talk to other software. Your mobile app needs to fetch weather data, your website needs to save user profiles, and your smart fridge needs to know if you are out of milk (seriously, why?).

This is where Web APIs come in. Today, we are going to turn your C# logic into a global service accessible by the world.


1. What is a Web API and RESTful Architecture? ๐ŸŒ

The Problem: The Language Barrier

Imagine you have a C# application, a website written in JavaScript, and an iPhone app written in Swift. They all need to share the same database of "Cute Cat Photos."

  • The C# app speaks objects and classes.
  • The JavaScript app speaks JSON.
  • The iPhone app speaks Swift structs.

They are like three people at a dinner party who don't speak the same language. How do they exchange data without chaos?

The Solution: The API (Application Programming Interface)

An API is a mediator. Itโ€™s a set of definitions and protocols that allows one piece of software to talk to another. In the web world, we use Web APIs.

The industry standard for how these APIs should behave is called REST (Representational State Transfer).

The Concept: RESTful Architecture

Definition: REST is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. It typically uses JSON (JavaScript Object Notation) as the common language.

Think of REST as the "Grammar Rules" of the web conversation.

  1. Client-Server: The Frontend (Client) and Backend (Server) are separate. You can change the code on one without breaking the other, as long as the message format stays the same.
  2. Stateless: The server doesn't remember the last conversation. Every request must contain all the information needed to complete it. (The server is like Dory from Finding Nemoโ€”"Hi, I'm a server. Oh look, a request! Hi, I'm a server.")
  3. Uniform Interface: All API requests look consistent (URLs, HTTP methods).

Fun Fact ๐Ÿฆ„: The term "REST" was coined by Roy Fielding in his PhD dissertation in 2000. Imagine writing a homework assignment that dictates how the entire modern internet works 20 years later. Talk about extra credit.


2. Setting Up & Creating Controllers/Routing ๐ŸŽฎ

Let's get our hands dirty. We are going to build an API for a "SuperHero Registry".

๐Ÿ› ๏ธ Industry Standard Setup (The Boilerplate)

We don't manually create files anymore. We use the .NET CLI (Command Line Interface). Open your terminal/command prompt.

bash
# create a new Web API project
dotnet new webapi -n SuperHeroAPI

# Enter the folder
cd SuperHeroAPI

# Open in VS Code (optional but recommended)
code .

Note: In .NET 6/7/8/9+, this template uses "Minimal APIs" by default or Controller-based APIs depending on flags. We will focus on Controller-based APIs as they are structurally better for large enterprise applications.

The Problem: Traffic Control

You have a server running. A user sends a request to https://your-site.com/api/heroes. How does the application know which specific C# method should run to handle that URL?

The Solution: Controllers and Routing

Definition: A Controller is a class used to group action methods that handle HTTP requests. Routing is the mechanism that maps the incoming URL to those specific methods.

In ASP.NET Core, a Controller is just a class that inherits from ControllerBase.

Industry Tip ๐Ÿ’ผ: Use ControllerBase, not Controller. The Controller class adds support for "Views" (HTML pages), which we don't need in an API. ControllerBase is lighter and faster.

The Code: Your First Controller

Create a file Controllers/SuperHeroController.cs:

csharp
using Microsoft.AspNetCore.Mvc;

namespace SuperHeroAPI.Controllers
{
    // 1. This attribute tells .NET "This class is an API Controller"
    // It enables automatic validation and smart error handling.
    [ApiController] 
    
    // 2. The Route attribute defines the URL pattern.
    // [controller] is a wildcard that gets replaced by the class name (minus "Controller").
    // So this becomes "api/SuperHero"
    [Route("api/[controller]")] 
    public class SuperHeroController : ControllerBase
    {
        // We will add methods here soon!
    }
}

3. Handling HTTP Requests (The CRUD) ๐Ÿ“ฆ

The Problem: Intent

If a user visits a URL, are they trying to get data, save new data, or delete data? The URL api/heroes looks the same for all of them.

The Solution: HTTP Verbs

We use HTTP Verbs to define the intent of the action. This maps perfectly to CRUD (Create, Read, Update, Delete).

HTTP Verb CRUD Operation Meaning
GET Read "Hey, give me the list of heroes."
POST Create "Here is a new hero, save them."
PUT Update "Replace the hero at ID 5 with this new data."
DELETE Delete "Get rid of this hero."

Let's flesh out our Controller.

Pre-requisite: Imagine we have a simple class Hero.

csharp
public class Hero 
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string SuperPower { get; set; } = string.Empty;
}

A. GET (Read)

We use [HttpGet] to mark a method for fetching data.

csharp
[HttpGet]
public ActionResult<List<Hero>> GetHeroes()
{
    var heroes = new List<Hero> 
    {
        new Hero { Id = 1, Name = "Spider-Man", SuperPower = "Webs" },
        new Hero { Id = 2, Name = "Iron Man", SuperPower = "Money" }
    };
    
    // Returns HTTP 200 OK with the JSON data
    return Ok(heroes); 
}

What happens under the hood: ASP.NET Core automatically takes your C# List, serializes it into JSON text, sets the Content-Type header to application/json, and sends it back. Magic. โœจ

B. GET (Read One)

How do we get just one hero? We need a parameter in the URL.

csharp
// The "{id}" adds a route parameter. URL: api/SuperHero/5
[HttpGet("{id}")]
public ActionResult<Hero> GetHero(int id)
{
    // Imagine we search a DB here.
    if (id != 1) 
    {
        // Returns HTTP 404 Not Found
        return NotFound("Hero not found. Maybe they are on vacation?");
    }
    
    return Ok(new Hero { Id = 1, Name = "Spider-Man", SuperPower = "Webs" });
}

C. POST (Create)

Sending data to the server. We expect the data in the Body of the request.

csharp
[HttpPost]
public ActionResult<List<Hero>> AddHero([FromBody] Hero newHero)
{
    // In real life, save to DB here.
    
    // Returns HTTP 201 Created (Industry Standard for creating things)
    return CreatedAtAction(nameof(GetHero), new { id = newHero.Id }, newHero);
}

D. PUT (Update) vs DELETE

PUT replaces the whole object.

csharp
[HttpPut("{id}")]
public ActionResult UpdateHero(int id, Hero request)
{
    // Find hero by id, update properties...
    return Ok("Hero Updated!");
}

[HttpDelete("{id}")]
public ActionResult DeleteHero(int id)
{
    // Find hero, remove from list...
    return Ok("Hero Deleted!");
}

Warning โš ๏ธ: Never use a GET request to delete data. Search engines (like Google) crawl links using GET. If you make a "Delete" link accessible via GET, GoogleBot might accidentally wipe your entire database just by browsing your site. That would be a very bad day.


4. Dependency Injection (DI) in ASP.NET Core ๐Ÿ’‰

This is the concept that separates "Junior" code from "Senior" code.

The Problem: The Hard-Coded Battery

Imagine you are building a toy robot.

  • Bad Way: You solder the battery directly inside the robot. If the battery dies or you want to upgrade to a rechargeable one, you have to melt the solder and break the robot to change it.
  • Code Equivalent: var service = new HeroService(); inside your controller. Your controller is now "soldered" to that specific service. You can't test the controller without the real service (which might talk to a real DB).

The Solution: Dependency Injection

Definition: DI is a design pattern where a class requests its dependencies from an external source rather than creating them itself.

Analogy: Instead of soldering the battery, you add a Battery Slot. You don't care what battery is put in there (Duracell, Energizer, or a fake test battery), as long as it fits the slot.

How to Implement DI in 3 Steps

Step 1: Create the Interface (The Slot Shape)

csharp
public interface IHeroService
{
    List<Hero> GetAllHeroes();
}

Step 2: Create the Implementation (The Battery)

csharp
public class HeroService : IHeroService
{
    public List<Hero> GetAllHeroes()
    {
        return new List<Hero> { /* database logic here */ };
    }
}

Step 3: Register in Program.cs (The Warehouse)

This tells ASP.NET: "Whenever a controller asks for IHeroService, give them a HeroService."

Open Program.cs:

csharp
var builder = WebApplication.CreateBuilder(args);

// ... other config

// Register the service
// We have three lifetimes (Lifetimes are crucial interview questions!):
// 1. AddTransient: Created every time it's requested. (Lightweight)
// 2. AddScoped: Created once per HTTP request. (Most common for DB contexts)
// 3. AddSingleton: Created once and lives forever while the app runs. (Caching)

builder.Services.AddScoped<IHeroService, HeroService>();

var app = builder.Build();

Step 4: Inject into Controller (Plug it in)

We use Constructor Injection.

csharp
[ApiController]
[Route("api/[controller]")]
public class SuperHeroController : ControllerBase
{
    private readonly IHeroService _heroService;

    // The container automatically passes the service here!
    public SuperHeroController(IHeroService heroService)
    {
        _heroService = heroService;
    }

    [HttpGet]
    public ActionResult<List<Hero>> Get()
    {
        // We use the injected service
        return Ok(_heroService.GetAllHeroes());
    }
}

Now your code is:

  1. Testable: You can inject a fake service for unit tests.
  2. Maintainable: Change HeroService logic without touching the Controller.
  3. Loose coupled: The controller doesn't know how data is fetched, just that it is fetched.

๐Ÿ“š Resources & References

Happy Coding! Go build something that talks to the world! ๐Ÿš€

Challenge

Your task is to create a complete ASP.NET Core controller for managing Product resources. This controller must handle all standard CRUD (Create, Read, Update, Delete) operations and follow RESTful principles.

You will be working with a pre-defined Product model and an IProductService interface. Your controller must correctly inject this service to perform data operations.

Requirements:

  1. Create a class named ProductsController that inherits from ControllerBase.
  2. Decorate the class with [ApiController] and a [Route] attribute to map it to the URL api/products.
  3. Implement a constructor that uses dependency injection to receive an instance of IProductService.
  4. Implement the following five public action methods:
    • GetProducts: A GET method to retrieve all products. It should be mapped to the controller's base route.
    • GetProduct: A GET method that accepts an int id to retrieve a single product. It should be mapped to "{id}". If the product is not found, it must return a NotFound result.
    • CreateProduct: A POST method that accepts a Product object from the request body to create a new product. Upon success, it must return a CreatedAtAction result, referencing the GetProduct action.
    • UpdateProduct: A PUT method that accepts an int id from the route and a Product object from the request body to update an existing product. It should return an appropriate success status code.
    • DeleteProduct: A DELETE method that accepts an int id to remove a product. It should return an appropriate success status code.

Expected result

Your solution should consist of a single C# class, ProductsController.

This class must satisfy the following criteria:

  • It must be decorated with the [ApiController] attribute.
  • It must have a [Route] attribute defining the path as api/products.
  • It must inherit from ControllerBase.
  • It must contain a private readonly field for IProductService.
  • It must have a public constructor that accepts an IProductService and assigns it to the private field.
  • It must contain five public methods, each corresponding to a CRUD operation:
    1. A GetProducts method with an [HttpGet] attribute, returning an ActionResult<IEnumerable<Product>>.
    2. A GetProduct method with an [HttpGet("{id}")] attribute, accepting an int id, and returning an ActionResult<Product>. This method must handle the case where a product is not found by returning NotFound().
    3. A CreateProduct method with an [HttpPost] attribute, accepting a Product object, and returning an ActionResult<Product>. The return statement should use CreatedAtAction.
    4. An UpdateProduct method with a [HttpPut("{id}")] attribute, accepting an int id and a Product object, and returning an IActionResult (e.g., NoContent()).
    5. A DeleteProduct method with a [HttpDelete("{id}")] attribute, accepting an int id, and returning an IActionResult (e.g., NoContent()).
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.