.NET Core Web API
Introduction
Section titled โ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
Section titled โ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 MyApiNavigate to the project folder:
 cd MyApiRun the application:
 dotnet runFolder Structure
Section titled โFolder StructureโA typical .NET Core Web API project follows this structure:
MyApi/โ-- Controllers/โ   โโโ WeatherForecastController.csโ-- Models/โ-- Services/โ-- Program.csโ-- appsettings.jsonCreating a Controller
Section titled โ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
Section titled โ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
Section titled โ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
Section titled โ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
Section titled โ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
Section titled โ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! ๐