.NET Core Web API
Introduction
.NET Core Web API is a framework for building scalable and high-performance RESTful services using .NET Core. It provides powerful features such as dependency injection, middleware pipeline, and built-in support for authentication and authorization.
Setting Up a .NET Core Web API Project
To create a new .NET Core Web API project, use the following command:
dotnet new webapi -n MyApi
Navigate to the project folder:
cd MyApi
Run the application:
dotnet run
Folder Structure
A typical .NET Core Web API project follows this structure:
MyApi/│-- Controllers/│ ├── WeatherForecastController.cs│-- Models/│-- Services/│-- Program.cs│-- appsettings.json
Creating a Controller
Controllers handle incoming HTTP requests and return responses. Example:
[ApiController][Route("api/[controller]")]public class ProductsController : ControllerBase{ [HttpGet] public IActionResult Get() { return Ok(new { message = "Hello from API" }); }}
Dependency Injection
.NET Core has built-in dependency injection. Register services in Program.cs
:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddScoped<IMyService, MyService>();
Inject into controllers:
public class MyController : ControllerBase{ private readonly IMyService _service; public MyController(IMyService service) { _service = service; }}
Middleware Pipeline
Middleware are components that handle requests and responses. Configure in Program.cs
:
var app = builder.Build();app.UseRouting();app.UseAuthorization();app.MapControllers();app.Run();
Authentication & Authorization
To add JWT authentication:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://your-identity-server"; options.Audience = "your-api"; });
Apply [Authorize]
to controllers:
[Authorize]public class SecureController : ControllerBase{ [HttpGet] public IActionResult GetSecureData() { return Ok("This is a secured endpoint"); }}
Configuring Swagger
Add Swagger for API documentation:
builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();
Enable it in Program.cs
:
app.UseSwagger();app.UseSwaggerUI();
Run the application and access https://localhost:<port>/swagger
.
Conclusion
.NET Core Web API is a powerful framework for building RESTful services. It provides built-in support for dependency injection, middleware, authentication, and more. By following best practices, you can build scalable and maintainable APIs efficiently.
Happy coding! 🚀