Program.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. .AddJsonOptions(options =>
  14. {
  15. // Use camelCase for JSON property names (categoryId instead of CategoryId)
  16. options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
  17. });
  18. // Add DbContext with Oracle provider
  19. var connectionString = builder.Configuration.GetSection("Connection").Value;
  20. builder.Services.AddDbContext<ModelContext>(options =>
  21. options.UseOracle(connectionString));
  22. // Add Business Services
  23. builder.Services.AddScoped<IUserBusiness, UserBusinessImpl>();
  24. builder.Services.AddScoped<IArticleBusiness, ArticleBusinessImpl>();
  25. builder.Services.AddScoped<IContentBusiness, ContentBusinessImpl>();
  26. // Configure CORS - Allow frontend to access APIs
  27. builder.Services.AddCors(options =>
  28. {
  29. options.AddPolicy("AllowFrontend", policy =>
  30. {
  31. policy.WithOrigins(
  32. "http://localhost:3000", // React development
  33. "http://localhost:5173", // Vite development
  34. "http://localhost:4200", // Angular development
  35. "http://simgetgo.vn", // Production domain
  36. "http://simgetgo.com", // Production www domain
  37. "https://simgetgo.vn", // Production www domain
  38. "https://simgetgo.com" // Production www domain
  39. )
  40. .AllowAnyMethod()
  41. .AllowAnyHeader()
  42. .AllowCredentials();
  43. });
  44. });
  45. // Configure JWT Authentication
  46. var jwtKey = builder.Configuration["Jwt:Key"] ?? "EsimLaoSecretKey1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCD";
  47. var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "EsimLao";
  48. var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "EsimLaoClient";
  49. builder.Services.AddAuthentication(options =>
  50. {
  51. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  52. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  53. })
  54. .AddJwtBearer(options =>
  55. {
  56. options.TokenValidationParameters = new TokenValidationParameters
  57. {
  58. ValidateIssuer = true,
  59. ValidateAudience = true,
  60. ValidateLifetime = true,
  61. ValidateIssuerSigningKey = true,
  62. ValidIssuer = jwtIssuer,
  63. ValidAudience = jwtAudience,
  64. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtKey))
  65. };
  66. });
  67. // Add Swagger for API documentation
  68. builder.Services.AddEndpointsApiExplorer();
  69. builder.Services.AddSwaggerGen();
  70. var app = builder.Build();
  71. // Initialize ConfigManager to load configs from database
  72. using (var scope = app.Services.CreateScope())
  73. {
  74. var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
  75. try
  76. {
  77. logger.LogInformation("Initializing ConfigManager...");
  78. Esim.Apis.Singleton.ConfigManager.Instance.Initialize();
  79. logger.LogInformation("ConfigManager initialized successfully");
  80. // Start background refresh task
  81. Task.Run(() => Esim.Apis.Singleton.ConfigManager.Instance.RefreshConfigs());
  82. }
  83. catch (Exception ex)
  84. {
  85. logger.LogError(ex, "Failed to initialize ConfigManager");
  86. }
  87. }
  88. app.UseSwagger();
  89. app.UseSwaggerUI();
  90. // Configure the HTTP request pipeline.
  91. //if (app.Environment.IsDevelopment())
  92. //{
  93. // app.UseSwagger();
  94. // app.UseSwaggerUI();
  95. //}
  96. //else
  97. //{
  98. // app.UseExceptionHandler("/Home/Error");
  99. // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  100. // app.UseHsts();
  101. //}
  102. // Only redirect to HTTPS in production
  103. if (!app.Environment.IsDevelopment())
  104. {
  105. app.UseHttpsRedirection();
  106. }
  107. app.UseRouting();
  108. // Enable CORS - MUST be after UseRouting and before UseAuthentication
  109. app.UseCors("AllowFrontend");
  110. app.UseAuthentication();
  111. app.UseAuthorization();
  112. app.MapStaticAssets();
  113. app.MapControllerRoute(
  114. name: "default",
  115. pattern: "{controller=Home}/{action=Index}/{id?}")
  116. .WithStaticAssets();
  117. app.MapControllers();
  118. app.Run();