ASP.NET Core Web API Documentation

Build modern, high-performance, cross-platform APIs.

Introduction to ASP.NET Core Web API

ASP.NET Core Web API is a framework for building web APIs that can be used by a broad range of clients, including browsers and mobile devices. It's a powerful and flexible platform that allows you to build robust, scalable, and high-performance APIs.

Key features include:

  • Cross-Platform: Runs on Windows, macOS, and Linux.
  • High Performance: Optimized for speed and efficiency.
  • Open Source and Community-Driven: Developed in the open with community contributions.
  • Modern Development Practices: Supports dependency injection, asynchronous programming, and more.

Prerequisites

Before you start developing ASP.NET Core Web APIs, ensure you have the following installed:

  • .NET SDK (latest stable version recommended)
  • A code editor, such as Visual Studio, Visual Studio Code, or JetBrains Rider.

You can download the .NET SDK from the official dotnet.microsoft.com website.

Creating Your First API

You can create a new ASP.NET Core Web API project using the .NET CLI:

dotnet new webapi -n MyFirstApi
cd MyFirstApi
dotnet run

This command creates a new Web API project named MyFirstApi, sets up a basic project structure, and includes a sample WeatherForecastController.

Core Concepts

Routing

Routing maps incoming HTTP requests to specific action methods in your controllers. ASP.NET Core uses a convention-based routing system that can be configured in Program.cs (or Startup.cs in older versions).

A common routing template is:

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

This template defines how URLs are parsed. For example, a URL like /api/products/5 would map to the Get action in the ProductsController with an ID of 5.

Controllers

Controllers are classes that handle incoming HTTP requests. They are typically located in the Controllers folder and inherit from ControllerBase or Controller.

Example controller:

using Microsoft.AspNetCore.Mvc;

namespace MyFirstApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return Ok(new[] { "Product 1", "Product 2" });
    }

    [HttpGet("{id}")]
    public ActionResult<string> GetById(int id)
    {
        if (id < 1)
        {
            return BadRequest("Product ID must be positive.");
        }
        // Assume we retrieve product from a database
        return Ok($"Product with ID: {id}");
    }
}

The [ApiController] attribute enables API-specific behaviors like automatic model validation and binding source inference.

The [Route("api/[controller]")] attribute sets up a base route for the controller, where [controller] is replaced by the controller name (e.g., api/Products).

Action Methods

Action methods are public methods within a controller that handle specific HTTP requests. They are decorated with HTTP verb attributes like [HttpGet], [HttpPost], [HttpPut], [HttpDelete], etc.

Action methods can return various types, including:

  • IActionResult: Provides full control over the HTTP response, including status codes and headers.
  • ActionResult<T>: A convenient way to return either a value of type T (which defaults to a 200 OK response) or an IActionResult.
  • Specific types like string, int, or custom objects, which are automatically wrapped in a 200 OK response.

Model Binding

Model binding is the process of taking incoming request data (from the URL, query string, form body, etc.) and creating a .NET object instance. This object can then be passed as a parameter to an action method.

By default, ASP.NET Core tries to bind parameters from various sources. You can explicitly specify the source using attributes like [FromRoute], [FromQuery], [FromBody], [FromHeader], and [FromForm].

[HttpPost]
public IActionResult CreateProduct([FromBody] ProductModel product)
{
    // ... save product ...
    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}

public class ProductModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Request Processing

ASP.NET Core processes requests through a pipeline of middleware. Each middleware component can perform specific tasks, such as authentication, routing, or exception handling.

In Program.cs, you configure the request pipeline:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Response Creation

Web APIs communicate using HTTP. ASP.NET Core makes it easy to construct HTTP responses, including setting status codes, headers, and the response body.

Common return types and methods:

  • Ok(object value): Returns an HTTP 200 OK response with the specified value.
  • NotFound(): Returns an HTTP 404 Not Found response.
  • BadRequest(object error): Returns an HTTP 400 Bad Request response.
  • CreatedAtAction(...): Returns an HTTP 201 Created response, often used after a POST operation.
  • NoContent(): Returns an HTTP 204 No Content response.

Dependency Injection

ASP.NET Core has a built-in, lightweight dependency injection (DI) container. DI is a design pattern used to achieve inversion of control and loosely coupled architecture. It's essential for making your code more testable and maintainable.

Register services in Program.cs:

builder.Services.AddScoped<IProductService, ProductService>();

Inject services into controllers:

public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    // ... action methods using _productService ...
}

Advanced Topics

Authentication & Authorization

Secure your API by implementing authentication (verifying the identity of the user) and authorization (determining what actions the authenticated user can perform).

ASP.NET Core supports various authentication schemes like JWT Bearer tokens, OAuth, OpenID Connect, and cookies. Authorization can be implemented using roles, policies, or custom requirements.

Key NuGet packages include:

  • Microsoft.AspNetCore.Authentication.JwtBearer
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore

Data Access with EF Core

Entity Framework Core (EF Core) is a powerful Object-Relational Mapper (ORM) for .NET. It allows you to work with databases using .NET objects.

To use EF Core:

  1. Install the necessary EF Core NuGet packages (e.g., Microsoft.EntityFrameworkCore.SqlServer).
  2. Define your entity classes and a DbContext.
  3. Register your DbContext in Program.cs.
  4. Inject the DbContext into your services or controllers to perform database operations.

API Testing

Thorough testing is crucial for any API. ASP.NET Core provides excellent support for unit testing and integration testing.

  • Unit Tests: Test individual components (e.g., services, models) in isolation. Use mocking frameworks like Moq.
  • Integration Tests: Test the API's behavior with its dependencies (e.g., database, other services). Use the TestServer provided by Microsoft.AspNetCore.Mvc.Testing.

Deployment

ASP.NET Core Web APIs can be deployed to various environments, including:

  • IIS on Windows
  • Kestrel on Linux/macOS
  • Docker containers
  • Cloud platforms like Azure App Service, AWS Elastic Beanstalk, etc.

Ensure you publish your application correctly for the target environment.