ASP.NET Core Web API

This documentation covers building Web APIs with ASP.NET Core, a high-performance, cross-platform framework for building modern, cloud-based, Internet-connected applications. You can build and run your ASP.NET Core Web API applications on Windows, macOS, and Linux.

Introduction to ASP.NET Core Web API

ASP.NET Core Web API is a framework for building HTTP services that can be consumed by a broad range of clients, including browsers and mobile devices. It's built on top of ASP.NET Core, providing a robust and scalable foundation.

Getting Started

Follow these steps to create your first ASP.NET Core Web API project:

  1. Create a New Project: Use the .NET CLI or Visual Studio to create a new ASP.NET Core Web API project.
  2. dotnet new webapi -n MyWebApi
    cd MyWebApi
    dotnet run
  3. Explore Project Structure: Understand the key files and folders in a Web API project, such as Program.cs, Controllers/, and appsettings.json.
  4. Create Your First Endpoint: Define a simple controller and action method to return data.

Core Concepts

Controllers

Controllers are classes that handle incoming HTTP requests. They typically inherit from ControllerBase and contain action methods that are executed when a specific route is matched.

using Microsoft.AspNetCore.Mvc;

namespace MyWebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase
    {
        // Action method to get all products
        [HttpGet]
        public IActionResult GetAll()
        {
            // Dummy data for demonstration
            var products = new[] {
                new { Id = 1, Name = "Laptop", Price = 1200.00m },
                new { Id = 2, Name = "Mouse", Price = 25.00m },
                new { Id = 3, Name = "Keyboard", Price = 75.00m }
            };
            return Ok(products);
        }

        // Action method to get a specific product by ID
        [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            // Dummy data for demonstration
            var products = new[] {
                new { Id = 1, Name = "Laptop", Price = 1200.00m },
                new { Id = 2, Name = "Mouse", Price = 25.00m },
                new { Id = 3, Name = "Keyboard", Price = 75.00m }
            };
            var product = products.FirstOrDefault(p => p.Id == id);
            if (product == null)
            {
                return NotFound(); // Returns a 404 Not Found response
            }
            return Ok(product); // Returns a 200 OK response with the product
        }
    }
}

Routing

ASP.NET Core Web API uses attribute routing and convention-based routing. Attribute routing is generally preferred for its explicitness.

Model Binding and Validation

The framework automatically binds incoming request data (from the request body, route values, query string, etc.) to action method parameters. Model validation ensures that incoming data is valid.

Tip:

Use the [FromBody], [FromRoute], [FromQuery], and [FromHeader] attributes to explicitly control how parameters are bound.

// Example using FromBody
[HttpPost]
public IActionResult CreateProduct([FromBody] Product newProduct)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    // ... logic to save the new product ...
    return CreatedAtAction(nameof(GetById), new { id = newProduct.Id }, newProduct);
}

Response Handling

Action methods return various IActionResult types to represent the HTTP response. Common examples include:

Advanced Topics

Asynchronous Programming

Embrace asynchronous programming for I/O-bound operations to improve scalability and responsiveness.

[HttpGet]
public async Task<IActionResult> GetProductsAsync()
{
    var products = await _productRepository.GetAllAsync();
    return Ok(products);
}

Dependency Injection

ASP.NET Core has built-in support for dependency injection, making it easy to manage services and dependencies.

Note:

Register your services in Program.cs using builder.Services.AddScoped<IProductRepository, ProductRepository>();.

Error Handling

Implement robust error handling to provide meaningful feedback to API consumers.

Authentication and Authorization

Secure your API endpoints using various authentication schemes (JWT, OAuth, etc.) and authorization policies.

Resources