IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| REST principles and API Design | Versioning WEB API in .net core | |
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
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.
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();
[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 }
});
}
/api/v1/) for backward compatibility.| Advantage | Description |
|---|---|
| β‘ High Performance | Built for speed and scalability |
| π Secure | Supports modern authentication and authorization |
| π§© Modular | Lightweight and extensible |
| π οΈ Tooling | Excellent support in Visual Studio and CLI |
| π Cross-Platform | Runs on Windows, Linux, and macOS |
| Disadvantage | Description |
|---|---|
| π Learning Curve | Can be steep for beginners |
| π Frequent Updates | Requires keeping up with .NET releases |
| π§΅ Real-Time Limitations | REST is not ideal for real-time (use SignalR or WebSockets) |
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.
TodoApi) β Next.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.).
https://localhost:<port>/swagger.TodoController.cs β Add.Create a simple in-memory to-do API.
TodoItem modelRight-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; }
}
TodoController logicReplace 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();
}
}
https://localhost:<port>/swagger.{ "name": "walk dog", "isComplete": false }.[Required], [Range]) or FluentValidation. | REST principles and API Design | Versioning WEB API in .net core | |