Web API Development with ASP.NET Core: A Comprehensive Tutorial

Overview

ASP.NET Core provides a robust and versatile framework for developing RESTful APIs. In this comprehensive tutorial, we will discuss the basics of developing web APIs using ASP.NET Core in .NET 8. We will cover essential topics such as routing, controllers, and middleware to guide you through the process of creating powerful and scalable APIs.

Prerequisites

Make sure you have the following installed before we begin:

.NET SDK 8.0 or later (Download .NET SDK)

Creating a New ASP.NET Core Web API Project

The first step is to create an ASP.NET Core Web API project.

dotnet new webapi -n ZrWebApi

cd ZryWebApi

The following command creates a new Web API project called "ZrWebApi."

Understanding Routing

A web API's routing defines how incoming requests are matched to the proper endpoint. ASP.NET Core defines routes with attribute routing.

Open Controllers/WeatherForecastController.cs and modify it as follows:

[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

By setting the [Route] attribute on the controller, all endpoints in this controller will be relative to /api/WeatherForecast.

Working with Controllers

Let's build a custom controller to manage a list of products. Controllers handle incoming requests, execute logic, and return responses.

Add a new file to the Controllers folder called ProductsController.cs.

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly List<Product> _products = new List<Product>
    {
        new Product { Id = 1, Name = "Product A", Price = 20.99 },
        new Product { Id = 2, Name = "Product B", Price = 15.49 },
        new Product { Id = 3, Name = "Product C", Price = 30.00 },
    };

    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        return Ok(_products);
    }

    [HttpGet("{id}")]
    public ActionResult<Product> GetProductById(int id)
    {
        var product = _products.FirstOrDefault(p => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }

        return Ok(product);
    }

    [HttpPost]
    public ActionResult<Product> CreateProduct(Product product)
    {
        product.Id = _products.Count + 1;
        _products.Add(product);
        return CreatedAtAction(nameof(GetProductById), new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public ActionResult<Product> 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 Ok(existingProduct);
    }

    [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();
    }
}

We have created endpoints to get a list of products, get a specific product by ID, create a new product, update an existing product, and delete a product in this example.

Middleware in ASP.NET Core

It is part of ASP.NET Core's pipeline that processes requests and responses. It is used for logging, authentication, and handling exceptions.

Add middleware to Startup.cs so that CORS is enabled and exceptions are handled:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseCors(builder =>
    {
        builder.AllowAnyOrigin();
        builder.AllowAnyMethod();
        builder.AllowAnyHeader();
    });

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

To provide meaningful error responses, this middleware configuration enables CORS across all origins, methods, and headers.

Testing the Web API

Let's test our simple Web API now that we've created it.

Run the API

dotnet run

Use a web browser or a Postman tool to request these endpoints.

Get all products:

GET http://localhost:5000/api/products

Get a product by ID:

GET http://localhost:5000/api/products/1

Create a new product:

POST http://localhost:5000/api/products 

 Body: { "name": "New Product", "price": 25.99 }

Update a product:

PUT http://localhost:5000/api/products/1

Body: { "name": "Updated Product", "price": 30.99 }

Delete a product:

DELETE http://localhost:5000/api/products/1

Summary

In this tutorial, you will learn how to build a Web API using ASP.NET Core in .NET 8. We will cover routing, controllers, and middleware. ASP.NET Core's simplicity and flexibility make it an ideal choice for developing robust and scalable APIs. As you continue to explore and develop with ASP.NET Core, you can dig deeper into topics like authentication, versioning, and testing to further enhance your API development skills. Please do not forget to follow me on my LinkedIn profile https://www.linkedin.com/in/ziggyrafiq/ 

Happy Coding