Program.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. using System.Text;
  2. using Common.Global;
  3. using Database.Database;
  4. using Esim.Apis.Business;
  5. using Microsoft.AspNetCore.Authentication.JwtBearer;
  6. using Microsoft.EntityFrameworkCore;
  7. using Microsoft.IdentityModel.Tokens;
  8. var builder = WebApplication.CreateBuilder(args);
  9. // Set global configuration for use by singletons like ConfigManager
  10. GlobalConfig.Configuration = builder.Configuration;
  11. // Add services to the container.
  12. builder.Services.AddControllersWithViews();
  13. // Add DbContext with Oracle provider
  14. var connectionString = builder.Configuration.GetSection("Connection").Value;
  15. builder.Services.AddDbContext<ModelContext>(options =>
  16. options.UseOracle(connectionString));
  17. // Add Business Services
  18. builder.Services.AddScoped<IUserBusiness, UserBusinessImpl>();
  19. builder.Services.AddScoped<IArticleBusiness, ArticleBusinessImpl>();
  20. builder.Services.AddScoped<IContentBusiness, ContentBusinessImpl>();
  21. // Configure CORS - Allow frontend to access APIs
  22. builder.Services.AddCors(options =>
  23. {
  24. options.AddPolicy("AllowFrontend", policy =>
  25. {
  26. policy.WithOrigins(
  27. "http://localhost:3000", // React development
  28. "http://localhost:5173", // Vite development
  29. "http://localhost:4200", // Angular development
  30. "https://infigate.vn", // Production domain
  31. "https://www.infigate.vn" // Production www domain
  32. )
  33. .AllowAnyMethod()
  34. .AllowAnyHeader()
  35. .AllowCredentials();
  36. });
  37. });
  38. // Configure JWT Authentication
  39. var jwtKey = builder.Configuration["Jwt:Key"] ?? "EsimLaoSecretKey12345678901234567890";
  40. var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "EsimLao";
  41. var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "EsimLaoClient";
  42. builder.Services.AddAuthentication(options =>
  43. {
  44. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  45. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  46. })
  47. .AddJwtBearer(options =>
  48. {
  49. options.TokenValidationParameters = new TokenValidationParameters
  50. {
  51. ValidateIssuer = true,
  52. ValidateAudience = true,
  53. ValidateLifetime = true,
  54. ValidateIssuerSigningKey = true,
  55. ValidIssuer = jwtIssuer,
  56. ValidAudience = jwtAudience,
  57. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtKey))
  58. };
  59. });
  60. // Add Swagger for API documentation
  61. builder.Services.AddEndpointsApiExplorer();
  62. builder.Services.AddSwaggerGen();
  63. var app = builder.Build();
  64. // Initialize ConfigManager to load configs from database
  65. using (var scope = app.Services.CreateScope())
  66. {
  67. var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
  68. try
  69. {
  70. logger.LogInformation("Initializing ConfigManager...");
  71. Esim.Apis.Singleton.ConfigManager.Instance.Initialize();
  72. logger.LogInformation("ConfigManager initialized successfully");
  73. // Start background refresh task
  74. Task.Run(() => Esim.Apis.Singleton.ConfigManager.Instance.RefreshConfigs());
  75. }
  76. catch (Exception ex)
  77. {
  78. logger.LogError(ex, "Failed to initialize ConfigManager");
  79. }
  80. }
  81. app.UseSwagger();
  82. app.UseSwaggerUI();
  83. // Configure the HTTP request pipeline.
  84. //if (app.Environment.IsDevelopment())
  85. //{
  86. // app.UseSwagger();
  87. // app.UseSwaggerUI();
  88. //}
  89. //else
  90. //{
  91. // app.UseExceptionHandler("/Home/Error");
  92. // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  93. // app.UseHsts();
  94. //}
  95. app.UseHttpsRedirection();
  96. app.UseRouting();
  97. // Enable CORS - MUST be after UseRouting and before UseAuthentication
  98. app.UseCors("AllowFrontend");
  99. app.UseAuthentication();
  100. app.UseAuthorization();
  101. app.MapStaticAssets();
  102. app.MapControllerRoute(
  103. name: "default",
  104. pattern: "{controller=Home}/{action=Index}/{id?}")
  105. .WithStaticAssets();
  106. app.MapControllers();
  107. app.Run();