ASP.NET Core Web API

Build robust and scalable web services with .NET

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, mobile devices, and other applications. It allows you to create RESTful services, leveraging the flexibility and performance of the .NET ecosystem.

Key Concepts

Getting Started

The best way to learn is by doing. Follow these steps to create your first ASP.NET Core Web API project.

1. Project Setup

Use the .NET CLI to create a new Web API project:

dotnet new webapi -o MyWebApiProject

Navigate to the project directory:

cd MyWebApiProject

2. Creating Your First API Endpoint

Let's create a simple "Products" API. First, define a model:

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

Next, create a controller:

using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using System.Linq; [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.50m } }; [HttpGet] public ActionResult<IEnumerable<Product>> Get() { return Ok(_products); } [HttpGet("{id}")] public ActionResult<Product> Get(int id) { var product = _products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } [HttpPost] public ActionResult<Product> Post([FromBody] Product newProduct) { newProduct.Id = _products.Count > 0 ? _products.Max(p => p.Id) + 1 : 1; _products.Add(newProduct); return CreatedAtAction(nameof(Get), new { id = newProduct.Id }, newProduct); } }

3. Running Your API

Run your application using the .NET CLI:

dotnet run

You can then access your API endpoints. For example, to get all products, navigate to https://localhost:5001/api/products in your browser.

Advanced Topics

Explore these advanced concepts to build more sophisticated APIs:

Ready to dive deeper? Explore the official Microsoft documentation and tutorials.

Explore More Resources