Program.cs 4.9 KB

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