ASP.NET Core Web API Documentation

Introduction to ASP.NET Core Web API

ASP.NET Core Web API is a powerful framework for building HTTP services that can be consumed by a broad range of clients, including browsers and mobile devices. It allows you to build lightweight, high-performance, and cross-platform web APIs.

Key features include:

Getting Started with ASP.NET Core Web API

To start building a Web API project, you can use Visual Studio or the .NET CLI.

Using the .NET CLI:


dotnet new webapi -o MyWebApiProject
cd MyWebApiProject
dotnet run
            

This command creates a new Web API project named MyWebApiProject and automatically configures it to run.

Controllers

Controllers are classes that handle incoming HTTP requests. They are typically located in the Controllers folder of your project.

A basic controller might look like this:


using Microsoft.AspNetCore.Mvc;

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

The [ApiController] attribute enables API-specific behaviors, and [Route("api/[controller]")] sets up routing conventions.

Routing

ASP.NET Core Web API uses attribute routing for flexibility. You define routes using attributes like [HttpGet], [HttpPost], [HttpPut], [HttpDelete], etc., directly on action methods.

Route Templates

Route templates allow you to specify URL patterns. You can include parameters:


[HttpGet("{id}")]
public string GetProductById(int id)
{
    return $"Product ID: {id}";
}
            

This would match requests like /api/Products/123.

Action Methods

Action methods are public methods within a controller that handle specific HTTP requests based on their return type and route attributes.

Common return types include:

Request and Response Handling

Web APIs communicate using HTTP requests and responses. You can access request data (like query parameters, route parameters, and request body) and construct rich responses.

Example: Handling POST Request

POST /api/products

Request Body (JSON):


{
  "name": "New Gadget",
  "price": 99.99
}
                    

Controller Action:


using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateProduct([FromBody] Product newProduct)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        // Logic to save the newProduct
        return CreatedAtAction(nameof(GetProductById), new { id = 1 }, newProduct);
    }

    // Assume GetProductById is defined elsewhere
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
                    

Response (201 Created):


{
  "id": 1,
  "name": "New Gadget",
  "price": 99.99
}
                    

Model Binding

Model binding is the process of creating a .NET object from an incoming HTTP request. ASP.NET Core Web API automatically binds data from the request URL, query string, form data, and request body to your controller action parameters.

You can explicitly specify where to get data using attributes like:

Validation

Built-in validation using Data Annotations is supported. You can decorate your model classes with attributes like [Required], [StringLength], and [Range].


public class Product
{
    public int Id { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Name cannot be longer than 100 characters.")]
    public string Name { get; set; }

    [Range(0.01, 1000.00, ErrorMessage = "Price must be between 0.01 and 1000.00.")]
    public decimal Price { get; set; }
}
            

When [ApiController] is used, model state validation is automatically performed, and invalid requests will return a 400 Bad Request response with validation errors.

Dependency Injection

ASP.NET Core has first-class support for dependency injection (DI). You can register services in your Startup.cs (or Program.cs in .NET 6+) and inject them into your controllers.


// In Startup.cs (or Program.cs)
services.AddScoped<IProductRepository, ProductRepository>();

// In Controller
public class ProductsController : ControllerBase
{
    private readonly IProductRepository _repository;

    public ProductsController(IProductRepository repository)
    {
        _repository = repository;
    }

    [HttpGet]
    public IEnumerable<Product> Get()
    {
        return _repository.GetAll();
    }
}
            

Authentication and Authorization

ASP.NET Core Web API supports various authentication and authorization schemes, including JWT Bearer tokens, OAuth, and OpenID Connect. You can secure your API endpoints to ensure only authorized users can access them.

Use attributes like [Authorize] and [AllowAnonymous] on controllers or action methods.

Testing Web APIs

Unit testing and integration testing are crucial. ASP.NET Core provides tools and patterns to facilitate testing your API controllers, services, and middleware.

You can use the Microsoft.AspNetCore.Mvc.Testing package for integration tests that spin up an actual instance of your application.

Deployment

ASP.NET Core Web APIs can be deployed to various environments, including Windows servers (IIS), Linux servers (Kestrel), containers (Docker), and cloud platforms like Azure App Service.

Ensure you publish your application with the appropriate configuration for your target deployment environment.