Back
Building RESTful APIs with ASP.NET Core: A Complete Guide | YourSiteName

Building RESTful APIs with ASP.NET Core: A Complete Guide

ASP.NET Core provides a powerful and flexible framework for building RESTful APIs. This guide will walk you through the process, from setting up your project to deploying your API.

Setting Up Your ASP.NET Core API Project

First, create a new ASP.NET Core Web API project using the .NET CLI or Visual Studio.

Using the .NET CLI:


dotnet new webapi -n MyApi
cd MyApi
        

Project Structure

The project will include a default Controllers folder and a Program.cs file.

Creating Models and Controllers

Models represent the data your API will work with, and controllers handle the API endpoints.

Example: Creating a Product Model


// Models/Product.cs
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
        

Example: Creating a Products Controller


// Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private static readonly List<Product> _products = new List<Product>
    {
        new Product { Id = 1, Name = "Laptop", Price = 1200 },
        new Product { Id = 2, Name = "Mouse", Price = 25 }
    };

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

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

    [HttpPost]
    public ActionResult<Product> Post(Product product)
    {
        _products.Add(product);
        return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public IActionResult Put(int id, Product product)
    {
        var existingProduct = _products.Find(p => p.Id == id);
        if (existingProduct == null)
        {
            return NotFound();
        }
        existingProduct.Name = product.Name;
        existingProduct.Price = product.Price;
        return NoContent();
    }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        var product = _products.Find(p => p.Id == id);
        if (product == null)
        {
            return NotFound();
        }
        _products.Remove(product);
        return NoContent();
    }
}
        

Configuring Services and Middleware

In Program.cs, configure services and middleware for your API.


// Program.cs
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
        

Testing Your API

Use tools like Postman or Swagger UI to test your API endpoints.

SwaggerUI is automatically included with the default webapi template.

Data Persistence

For real-world APIs, you'll need to persist data using a database. Entity Framework Core is commonly used for this.

Deployment

Deploy your API to a hosting platform like Azure App Service, AWS Elastic Beanstalk, or a Docker container.

Conclusion

Building RESTful APIs with ASP.NET Core is straightforward and efficient. By following this guide, you can create robust and scalable APIs for your applications.