| 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
π 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
| 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 |
β οΈ Disadvantages
| 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) |
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
- Open Visual Studio β Create a new project.
- Select ASP.NET Core Web API template β Next.
- Configure project (e.g., name =
TodoApi) β Next. -
In Additional information:
- Select target framework (e.g., .NET 9.0).
- Ensure Enable OpenAPI support is checked (Swagger).
- Keep Use controllers checked.
- 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
- Run the project (Ctrl + F5 or IIS Express button).
- Browser opens Swagger UI, typically at
https://localhost:<port>/swagger. - Use Swaggerβs Try it out to call sample endpoints.
Step 4: Add a new controller
- In Solution Explorer, right-click Controllers β Add > Controller.
- Choose API Controller - Empty β Add.
- 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
- Run the app (Ctrl + F5).
- Open Swagger UI at
https://localhost:<port>/swagger. - 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.
| REST principles and API Design :👈 | 👉:Versioning WEB API in .net core |