ASP.NET Core Web API

Building HTTP services with ASP.NET Core.

What is ASP.NET Core Web API?

ASP.NET Core Web API is a framework for building HTTP services that can be accessed from a wide variety of clients, including browsers, mobile devices, and other server-side applications. It's built on top of ASP.NET Core, offering a lean, high-performance, and cross-platform solution for developing modern web services.

Key features include:

  • RESTful Services: Designed for creating RESTful HTTP services.
  • Cross-Platform: Runs on Windows, macOS, and Linux.
  • High Performance: Optimized for speed and efficiency.
  • Dependency Injection: Built-in support for dependency injection.
  • Cross-Cutting Concerns: Middleware pipeline for handling requests, authentication, authorization, and more.
  • Routing: Flexible routing mechanisms to map URLs to actions.
  • Model Binding and Validation: Automatic model binding and validation for request data.
  • Content Negotiation: Supports various content formats like JSON and XML.
  • Swagger/OpenAPI Integration: Seamless integration with Swagger for API documentation and testing.

Getting Started with Web API

Creating your first Web API project is straightforward:

  1. Create a New Project: Open Visual Studio or use the .NET CLI. Select the "ASP.NET Core Web API" template.
    dotnet new webapi -o MyWebApiProject
  2. Define Controllers: Controllers are classes that handle incoming HTTP requests. They typically inherit from ControllerBase.
    
    using Microsoft.AspNetCore.Mvc;
    
    [ApiController]
    [Route("[controller]")]
    public class ProductsController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "Product 1", "Product 2" };
        }
    
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return $"Product ID: {id}";
        }
    }
                            
  3. Configure Services and Middleware: In Program.cs (or Startup.cs in older versions), configure services and middleware.
    
    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();
                            

Key Concepts

Routing

Routing maps incoming HTTP requests to specific controller actions. You can use attributes like [Route] and HTTP verb attributes ([HttpGet], [HttpPost], etc.) for attribute routing.


[Route("api/v1/[controller]")]
public class OrdersController : ControllerBase
{
    [HttpGet("{orderId:int}")]
    public IActionResult GetOrder(int orderId) { ... }
}
                

Model Binding

Model binding automatically maps incoming request data (query strings, route data, form data, request body) to controller action parameters.


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

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    // ... other properties
}
                

Action Results

Action methods return IActionResult types, which represent the result of an action execution. Common types include Ok(), NotFound(), BadRequest(), Created(), and StatusCode().

Dependency Injection

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


public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

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

    [HttpGet]
    public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
    {
        var products = await _productService.GetAllAsync();
        return Ok(products);
    }
}
                

Swagger/OpenAPI

Integrate Swagger/OpenAPI for interactive API documentation.

  1. Add Swashbuckle NuGet packages:
    
    dotnet add package Swashbuckle.AspNetCore
                            
  2. Configure in Program.cs:
    
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    // ...
    
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty; // Serve the UI at the root
    });
                            

Advanced Topics

Best Practice: Use specific HTTP status codes to accurately represent the outcome of your API operations.
Security Note: Always validate and sanitize input from clients to prevent security vulnerabilities.