Swagger.
Swagger (OpenAPI) is a powerful tool that:
- Generates interactive API documentation
- Helps you test APIs right from the browser
- Makes your API self-descriptive for frontend teams and third-party users
How to configure Swagger?
var builder = WebApplication.CreateBuilder(args); // Add services builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); // For minimal API support builder.Services.AddSwaggerGen(); // 👈 Adds Swagger generator var app = builder.Build(); // Use middleware if (app.Environment.IsDevelopment()) { app.UseSwagger(); // 👈 Enables Swagger JSON app.UseSwaggerUI(); // 👈 Enables Swagger UI } app.UseAuthorization(); app.MapControllers(); app.Run();
builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "This is a sample Web API using Swagger.", Contact = new OpenApiContact { Name = "Probin Sah", Email = "probin@example.com" } }); });
What is CORS?
- If your Angular app runs on http://localhost:4200
- And your API runs on http://localhost:5000
How To Enable CORS in ASP.NET Core?
builder.Services.AddCors(options => { options.AddPolicy("AllowFrontendApp", policy => { policy .WithOrigins("http://localhost:4200") // Frontend URL .AllowAnyMethod() .AllowAnyHeader(); }); });
var app = builder.Build(); app.UseCors("AllowFrontendApp"); // 👈 Apply the policy app.UseAuthorization(); app.MapControllers(); app.Run();
- CORS allows your frontend (from another origin) to call your backend API.
- Without it, browsers block cross-origin calls for security.
- Use .WithOrigins, .AllowAnyMethod, .AllowAnyHeader to control access.
Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.