Previous REST principles and API Design Versioning WEB API in .net core Next

ASP.NET Core Web API (Controller-based) β€” Setup

Setting up an ASP.NET Core Web API is a great way to build scalable, maintainable, and secure backend services. Here's a step-by-step guide to help you get started, along with best practices and tips to make your API production-ready

πŸš€ Step-by-Step Setup: ASP.NET Core Web API

1. Create the Project
Use the .NET CLI or Visual Studio:

dotnet new webapi -n MyApiProject
cd MyApiProject

This scaffolds a basic API project with a WeatherForecastController.

2. Project Structure Overview

  • Controllers/ – API endpoints
  • Models/ – Data models
  • Services/ – Business logic
  • Repositories/ – Data access
  • DTOs/ – Data Transfer Objects
  • Middleware/ – Custom middleware

3. Configure Services in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Middleware
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run(); 

4. Create a Sample Controller

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() => Ok(new[] {
        new { Id = 1, Name = "Laptop", Price = 999.99 },
        new { Id = 2, Name = "Phone", Price = 499.99 }
    });
}

βœ… Best Practices

  • Use Dependency Injection for services and repositories.
  • Use DTOs to avoid exposing internal models.
  • Enable Swagger for API documentation.
  • Use FluentValidation or DataAnnotations for input validation.
  • Implement global exception handling via middleware.
  • Secure endpoints with JWT authentication and role-based authorization.
  • Use async/await for non-blocking I/O operations.
  • Version your API (e.g., /api/v1/) for backward compatibility.

⚠️ Precautions

  • Avoid exposing sensitive data.
  • Validate all incoming data.
  • Use HTTPS to encrypt traffic.
  • Implement Rate Limiting and logging.
  • Monitor performance and errors with tools like Serilog or Application Insights.

🌟 Advantages of ASP.NET Core Web API

AdvantageDescription
⚑ High PerformanceBuilt for speed and scalability
πŸ”’ SecureSupports modern authentication and authorization
🧩 ModularLightweight and extensible
πŸ› οΈ ToolingExcellent support in Visual Studio and CLI
🌍 Cross-PlatformRuns on Windows, Linux, and macOS

⚠️ Disadvantages

DisadvantageDescription
πŸ“š Learning CurveCan be steep for beginners
πŸ”„ Frequent UpdatesRequires keeping up with .NET releases
🧡 Real-Time LimitationsREST is not ideal for real-time (use SignalR or WebSockets)

ASP.NET Core Web API (Controller-based) β€” Setup in Visual Studio

An ASP.NET Core Web API can be set up in Visual Studio or with the .NET CLI. The steps below use Visual Studio for a controller-based API.

Prerequisites

  • Visual Studio: Visual Studio 2022 or later recommended.
  • .NET SDK: Latest .NET SDK (example: .NET 9.0) recommended.
  • Workloads: Ensure the "ASP.NET and web development" workload is installed.

Step 1: Create a new Web API project

  1. Open Visual Studio β†’ Create a new project.
  2. Select ASP.NET Core Web API template β†’ Next.
  3. Configure project (e.g., name = TodoApi) β†’ Next.
  4. In Additional information:
    • Select target framework (e.g., .NET 9.0).
    • Ensure Enable OpenAPI support is checked (Swagger).
    • Keep Use controllers checked.
  5. Click Create.

Step 2: Explore the default project

The template includes a runnable API with a sample WeatherForecastController.

Program.cs is the app entry point and typically looks like this:

<!-- Program.cs -->
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
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(); 

Controllers folder contains example controllers. launchSettings.json configures launch profiles (Swagger URL, etc.).

Step 3: Run and test the API

  1. Run the project (Ctrl + F5 or IIS Express button).
  2. Browser opens Swagger UI, typically at https://localhost:<port>/swagger.
  3. Use Swagger’s Try it out to call sample endpoints.

Step 4: Add a new controller

  1. In Solution Explorer, right-click Controllers β†’ Add > Controller.
  2. Choose API Controller - Empty β†’ Add.
  3. Name it TodoController.cs β†’ Add.

Step 5: Implement CRUD operations

Create a simple in-memory to-do API.

Add the TodoItem model

Right-click project β†’ Add > New Folder β†’ name it Models. Add class TodoItem.cs:

namespace TodoApi.Models;

public class TodoItem
{
public int Id { get; set; }
public string? Name { get; set; }
public bool IsComplete { get; set; }
} 

Add the TodoController logic

Replace the contents of TodoController.cs with:

using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;

namespace TodoApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
private static List<TodoItem> _todoItems = new List<TodoItem>();

[HttpGet]
public ActionResult<IEnumerable<TodoItem>> Get()
{
    return _todoItems;
}

[HttpGet("{id}")]
public ActionResult<TodoItem> Get(int id)
{
    var item = _todoItems.FirstOrDefault(t => t.Id == id);
    if (item == null)
    {
        return NotFound();
    }
    return item;
}

[HttpPost]
public ActionResult<TodoItem> Post(TodoItem todoItem)
{
    todoItem.Id = _todoItems.Count > 0 ? _todoItems.Max(t => t.Id) + 1 : 1;
    _todoItems.Add(todoItem);
    return CreatedAtAction(nameof(Get), new { id = todoItem.Id }, todoItem);
}

[HttpPut("{id}")]
public IActionResult Put(int id, TodoItem todoItem)
{
    if (id != todoItem.Id) return BadRequest();
    var existingItem = _todoItems.FirstOrDefault(t => t.Id == id);
    if (existingItem == null)
    {
        return NotFound();
    }
    existingItem.Name = todoItem.Name;
    existingItem.IsComplete = todoItem.IsComplete;
    return NoContent();
}

[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    var existingItem = _todoItems.FirstOrDefault(t => t.Id == id);
    if (existingItem == null)
    {
        return NotFound();
    }
    _todoItems.Remove(existingItem);
    return NoContent();
}
} 

Step 6: Test your new API endpoints

  1. Run the app (Ctrl + F5).
  2. Open Swagger UI at https://localhost:<port>/swagger.
  3. Test endpoints:
    • POST /api/Todo β€” add a new item with JSON body, e.g. { "name": "walk dog", "isComplete": false }.
    • GET /api/Todo β€” retrieve all items to confirm the new item exists.
    • Test GET by id, PUT to update, DELETE to remove.

Notes & Best Practices

  • Use Dependency Injection for repositories/services rather than static in-memory lists for production.
  • Use DTOs and model validation attributes ([Required], [Range]) or FluentValidation.
  • Use async/await for I/O-bound operations (database, external services).
  • Secure endpoints with authentication & authorization (e.g., JWT).
  • Enable CORS when the API is consumed from different domains.
  • Log and handle exceptions globally (middleware) and return appropriate HTTP status codes.
Back to Index
Previous REST principles and API Design Versioning WEB API in .net core Next
*