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.
- RESTful Principles: Learn how to design and implement APIs that adhere to RESTful architectural constraints.
- HTTP Verbs: Understand the use of HTTP methods like GET, POST, PUT, DELETE for performing operations.
- Routing: Configure how incoming requests are mapped to controller actions.
- Controllers: Create controller classes that handle incoming API requests.
Getting Started
Follow these steps to create your first ASP.NET Core Web API project:
- Create a New Project: Use the .NET CLI or Visual Studio to create a new ASP.NET Core Web API project.
- Explore Project Structure: Understand the key files and folders in a Web API project, such as
Program.cs
,Controllers/
, andappsettings.json
. - Create Your First Endpoint: Define a simple controller and action method to return data.
dotnet new webapi -n MyWebApi
cd MyWebApi
dotnet run
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.
- Route Attributes: Apply
[Route(...)]
attributes to controllers and action methods to define their endpoints. - HTTP Verb Attributes: Use attributes like
[HttpGet]
,[HttpPost]
,[HttpPut]
,[HttpDelete]
to specify the HTTP method handled by an action.
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:
Ok(object value)
: Returns a 200 OK response with a result.NotFound()
: Returns a 404 Not Found response.BadRequest()
: Returns a 400 Bad Request response.CreatedAtAction(...)
: Returns a 201 Created response.NoContent()
: Returns a 204 No Content response.
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.
- Global Exception Handling: Use middleware to catch unhandled exceptions.
- Validation Errors: Return detailed validation errors using
BadRequest(ModelState)
.
Authentication and Authorization
Secure your API endpoints using various authentication schemes (JWT, OAuth, etc.) and authorization policies.