From acca77e0161a5c10981bd25f6ab030491aa6c75f Mon Sep 17 00:00:00 2001 From: Syed Zohiab Ali <95756200+ZohaiAli@users.noreply.github.com> Date: Tue, 14 Oct 2025 14:46:36 +0500 Subject: [PATCH] Improve Program.cs: safe log folder creation, CORS policy, middleware order, and Serilog setup --- Presentation/ASPNET/Program.cs | 60 ++++++++++++++++++++++++++++++---- 1 file changed, 53 insertions(+), 7 deletions(-) diff --git a/Presentation/ASPNET/Program.cs b/Presentation/ASPNET/Program.cs index b30b3786..053bf842 100644 --- a/Presentation/ASPNET/Program.cs +++ b/Presentation/ASPNET/Program.cs @@ -1,21 +1,48 @@ using ASPNET.BackEnd; using ASPNET.BackEnd.Common.Middlewares; using ASPNET.FrontEnd; +using Serilog; var builder = WebApplication.CreateBuilder(args); -//>>> Create Logs folder for Serilog +//>>> Configure Serilog logging var logPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "app_data", "logs"); -if (!Directory.Exists(logPath)) +try { - Directory.CreateDirectory(logPath); + if (!Directory.Exists(logPath)) + { + Directory.CreateDirectory(logPath); + } } +catch (Exception ex) +{ + Console.WriteLine($"Failed to create logs directory: {ex.Message}"); +} + +// Configure Serilog +Log.Logger = new LoggerConfiguration() + .WriteTo.File(Path.Combine(logPath, "app.log"), rollingInterval: RollingInterval.Day) + .CreateLogger(); + +builder.Host.UseSerilog(); builder.Services.AddBackEndServices(builder.Configuration); builder.Services.AddFrontEndServices(); +// Configure CORS policy +builder.Services.AddCors(options => +{ + options.AddPolicy("AllowAll", policy => + { + policy.AllowAnyOrigin() + .AllowAnyHeader() + .AllowAnyMethod(); + }); +}); + var app = builder.Build(); +// Register backend services and routes app.RegisterBackEndBuilder(app.Environment, app, builder.Configuration); if (!app.Environment.IsDevelopment()) @@ -25,13 +52,32 @@ } app.UseRouting(); -app.UseCors(); -app.UseMiddleware(); + +// Apply CORS policy +app.UseCors("AllowAll"); + +// Authentication & Authorization app.UseAuthentication(); app.UseAuthorization(); -app.MapStaticAssets(); +// Global exception middleware should be after auth +app.UseMiddleware(); + +// Map static assets and frontend/backend routes +app.MapStaticAssets(); app.MapFrontEndRoutes(); app.MapBackEndRoutes(); -app.Run(); +// Safe startup +try +{ + app.Run(); +} +catch (Exception ex) +{ + Log.Fatal(ex, "Application failed to start"); +} +finally +{ + Log.CloseAndFlush(); +}