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.
This commit is contained in:
OlgunR
2026-01-19 08:34:40 +01:00
parent 289dba9b16
commit 28bab05980
2 changed files with 20 additions and 4 deletions

View File

@@ -5,7 +5,7 @@ using DbFirst.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using DbFirst.API.Middleware; using DbFirst.API.Middleware;
// TODO: create and add exception handling middleware - Done //TODO: create and add exception handling middleware
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -17,11 +17,21 @@ builder.Services.AddSwaggerGen();
// TODO: allow listed origins configured in appsettings.json // TODO: allow listed origins configured in appsettings.json
builder.Services.AddCors(options => builder.Services.AddCors(options =>
{ {
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
options.AddDefaultPolicy(policy => options.AddDefaultPolicy(policy =>
{
if (origins.Length > 0)
{
policy.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod();
}
else
{ {
policy.AllowAnyOrigin() policy.AllowAnyOrigin()
.AllowAnyHeader() .AllowAnyHeader()
.AllowAnyMethod(); .AllowAnyMethod();
}
}); });
}); });

View File

@@ -2,6 +2,12 @@
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd;TrustServerCertificate=True;" "DefaultConnection": "Server=SDD-VMP04-SQL17\\DD_DEVELOP01;Database=DD_ECM;User Id=sa;Password=dd;TrustServerCertificate=True;"
}, },
"Cors": {
"AllowedOrigins": [
"https://localhost:7276",
"http://localhost:5101"
]
},
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",