MSDN Documentation

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

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
  }
]

Further Reading