Files
DbFirst/DbFirst.API/Program.cs
OlgunR 28bab05980 Add configurable CORS support via appsettings.json
Introduce CORS configuration using allowed origins from appsettings.json. Updated Program.cs to read allowed origins from configuration and apply them to the CORS policy, defaulting to AllowAnyOrigin if none are specified. Also made minor formatting and comment improvements.
2026-01-19 08:34:40 +01:00

66 lines
1.9 KiB
C#

using DbFirst.Application.Catalogs;
using DbFirst.Domain.Repositories;
using DbFirst.Infrastructure;
using DbFirst.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using DbFirst.API.Middleware;
//TODO: create and add exception handling middleware
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// TODO: allow listed origins configured in appsettings.json
builder.Services.AddCors(options =>
{
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
options.AddDefaultPolicy(policy =>
{
if (origins.Length > 0)
{
policy.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod();
}
else
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
}
});
});
// TODO: Create extension method for this in Infrastructure layer in case of using in multiple projects
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// TODO: Create extension method for this in Application layer in case of using in multiple projects
builder.Services.AddAutoMapper(typeof(CatalogProfile).Assembly, typeof(ApplicationDbContext).Assembly);
builder.Services.AddScoped<ICatalogRepository, CatalogRepository>();
builder.Services.AddScoped<ICatalogService, CatalogService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<ExceptionHandlingMiddleware>();
app.UseHttpsRedirection();
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();