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
| Rate Limiting in .NET Core | Unit-Testing-in-ASP-NET-Core | |
📘 Swagger / OpenAPI Documentation in ASP.NET Core |
Swagger (now known as OpenAPI) is a specification for documenting RESTful APIs. It provides a user-friendly interface to explore and test endpoints, view request/response schemas, and generate client SDKs.
Swagger (OpenAPI) documentation is a standard, language-agnostic specification for describing REST APIs. It provides a blueprint that allows both humans and computers to understand an API's capabilities without accessing the source code. In ASP.NET Core, this is implemented using a NuGet package and middleware.
OpenAPI vs. Swagger:
dotnet add package Swashbuckle.AspNetCore
// Program.cs
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Run your application and navigate to /swagger in your browser to access the interactive API documentation.
Enable XML documentation in project settings, then configure Swagger to read the XML file.
// Program.cs
using System.Reflection;
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
/// <summary>
/// A controller for managing products.
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
/// <summary>
/// Gets a list of all products.
/// </summary>
/// <returns>A list of products.</returns>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public IEnumerable<string> Get()
{
return new string[] { "Product 1", "Product 2" };
}
}
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
Description = "Sample API for demonstration",
Contact = new OpenApiContact
{
Name = "Shivshanker",
Email = "shiv@example.com"
}
});
});
| Rate Limiting in .NET Core | Unit-Testing-in-ASP-NET-Core | |