Building Web APIs with ASP.NET Core
This section provides comprehensive documentation on creating robust and scalable Web APIs using ASP.NET Core. You'll learn about routing, controllers, model binding, attribute routing, content negotiation, and how to secure your APIs.
Key Concepts
- Controllers: The building blocks of your API, handling incoming requests and returning responses.
- Routing: How ASP.NET Core maps incoming HTTP requests to specific controller actions.
- Model Binding: The process of creating a .NET object from incoming request data.
- Attribute Routing: Defining routes directly on controller actions using attributes.
- HTTP Verbs: Understanding GET, POST, PUT, DELETE, and other methods.
- Response Formatting: Returning data in various formats like JSON and XML.
- Error Handling: Implementing consistent and informative error responses.
- Authentication & Authorization: Securing your API endpoints.
Getting Started with a Simple API
Let's create a basic API to manage a list of "Products".
1. Create a Project
Use the .NET CLI to create a new ASP.NET Core Web API project:
dotnet new webapi -n MyProductApi
cd MyProductApi
2. Define a Model
Create a simple model class, for example, in a Models
folder:
// Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
3. Create a Controller
Generate a controller to handle requests for products:
// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using MyProductApi.Models;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static List _products = new List
{
new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
new Product { Id = 2, Name = "Keyboard", Price = 75.00m }
};
[HttpGet]
public ActionResult> GetProducts()
{
return Ok(_products);
}
[HttpGet("{id}")]
public ActionResult GetProductById(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public ActionResult CreateProduct(Product newProduct)
{
newProduct.Id = _products.Count > 0 ? _products.Max(p => p.Id) + 1 : 1;
_products.Add(newProduct);
return CreatedAtAction(nameof(GetProductById), new { id = newProduct.Id }, newProduct);
}
[HttpPut("{id}")]
public IActionResult UpdateProduct(int id, Product updatedProduct)
{
var existingProduct = _products.FirstOrDefault(p => p.Id == id);
if (existingProduct == null)
{
return NotFound();
}
existingProduct.Name = updatedProduct.Name;
existingProduct.Price = updatedProduct.Price;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult DeleteProduct(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product == null)
{
return NotFound();
}
_products.Remove(product);
return NoContent();
}
}
4. Run the API
You can run your API using the .NET CLI:
dotnet run
The API will typically be available at https://localhost:5001
or http://localhost:5000
(check your launch settings).
Example Request: Getting all products
Method: GET
URL: /api/products
Expected Response (JSON):
[
{
"id": 1,
"name": "Laptop",
"price": 1200.00
},
{
"id": 2,
"name": "Keyboard",
"price": 75.00
}
]