ASP.
NET Core Web API Guide
ASP.NET Core Web API is a framework for building RESTful services using the ASP.NET Core platform.
It allows developers to expose endpoints that can be consumed by clients such as mobile apps, web apps,
and other services.
Getting Started
- Install .NET 8 SDK from https://dotnet.microsoft.com
- Create a new API project:
dotnet new webapi -n MyApiApp
- Run the project:
cd MyApiApp
dotnet run
Project Structure
- Program.cs: Entry point, middleware configuration
- Controllers/: Where your API controllers live
- appsettings.json: Configuration file
Creating a Simple Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
[HttpGet]
public IActionResult Get() => Ok(new[] { "Item1", "Item2" });
Model Binding
ASP.NET Core supports binding data from the request using attributes like:
- [FromQuery]
- [FromBody]
Page 1
ASP.NET Core Web API Guide
- [FromRoute]
- [FromHeader]
Dependency Injection
Services are added in Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
Injected into controllers:
public ProductsController(IProductService productService) { ... }
Middleware
Common middlewares include:
- UseRouting()
- UseAuthentication()
- UseAuthorization()
Versioning
Add API versioning via NuGet:
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Configure in Program.cs:
builder.Services.AddApiVersioning(opt => {
opt.DefaultApiVersion = new ApiVersion(1, 0);
opt.AssumeDefaultVersionWhenUnspecified = true;
});
Swagger Documentation
Add Swagger via Swashbuckle.AspNetCore:
dotnet add package Swashbuckle.AspNetCore
In Program.cs:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Page 2
ASP.NET Core Web API Guide
Security
- Use HTTPS
- Apply [Authorize] attribute
- Use JWT or OAuth2 for token-based authentication
Conclusion
ASP.NET Core Web API provides a fast, scalable way to build modern web services. Combine it with EF
Core, Swagger, and good architecture practices for best results.
Page 3