Enable Swagger and CROS in ASP.NET Core.

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?

If not already installed, add the package:

dotnet add package Swashbuckle.AspNetCore

Add Swagger services before building the app:
Example:
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();

You can enhance your Swagger UI by providing API details:
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?

CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers that restricts web apps from making requests to a different domain than the one that served the web page.

Why is it needed?
By default, browsers block cross-origin requests to protect users. For example:
  • If your Angular app runs on http://localhost:4200
  • And your API runs on http://localhost:5000
The browser blocks requests from the Angular app to the API unless CORS is explicitly enabled.

How To Enable CORS in ASP.NET Core?

Step 1: Add CORS Services in Program.cs
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowFrontendApp", policy =>
    {
        policy
            .WithOrigins("http://localhost:4200") // Frontend URL
            .AllowAnyMethod()
            .AllowAnyHeader();
    });
});

Step 2: Use CORS Middleware
Place it before UseAuthorization():
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.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS