Program.cs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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://simgetgo.vn", // Production www domain
  51. "https://simgetgo.com" // Production www domain
  52. )
  53. .AllowAnyMethod()
  54. .AllowAnyHeader()
  55. .AllowCredentials();
  56. }
  57. );
  58. });
  59. // Configure JWT Authentication
  60. var jwtKey =
  61. builder.Configuration["Jwt:Key"]
  62. ?? "EsimLaoSecretKey1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCD";
  63. var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "EsimLao";
  64. var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "EsimLaoClient";
  65. builder
  66. .Services.AddAuthentication(options =>
  67. {
  68. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  69. options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  70. })
  71. .AddJwtBearer(options =>
  72. {
  73. options.TokenValidationParameters = new TokenValidationParameters
  74. {
  75. ValidateIssuer = true,
  76. ValidateAudience = true,
  77. ValidateLifetime = true,
  78. ValidateIssuerSigningKey = true,
  79. ValidIssuer = jwtIssuer,
  80. ValidAudience = jwtAudience,
  81. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtKey))
  82. };
  83. });
  84. // Add Swagger for API documentation
  85. builder.Services.AddEndpointsApiExplorer();
  86. builder.Services.AddSwaggerGen();
  87. var app = builder.Build();
  88. // Initialize ConfigManager to load configs from database
  89. using (var scope = app.Services.CreateScope())
  90. {
  91. var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
  92. try
  93. {
  94. logger.LogInformation("Initializing ConfigManager...");
  95. Esim.Apis.Singleton.ConfigManager.Instance.Initialize();
  96. logger.LogInformation("ConfigManager initialized successfully");
  97. // Start background refresh task
  98. Task.Run(() => Esim.Apis.Singleton.ConfigManager.Instance.RefreshConfigs());
  99. }
  100. catch (Exception ex)
  101. {
  102. logger.LogError(ex, "Failed to initialize ConfigManager");
  103. }
  104. }
  105. app.UseSwagger();
  106. app.UseSwaggerUI();
  107. // Configure the HTTP request pipeline.
  108. //if (app.Environment.IsDevelopment())
  109. //{
  110. // app.UseSwagger();
  111. // app.UseSwaggerUI();
  112. //}
  113. //else
  114. //{
  115. // app.UseExceptionHandler("/Home/Error");
  116. // // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  117. // app.UseHsts();
  118. //}
  119. // Only redirect to HTTPS in production
  120. if (!app.Environment.IsDevelopment())
  121. {
  122. app.UseHttpsRedirection();
  123. }
  124. app.UseRouting();
  125. // Enable CORS - MUST be after UseRouting and before UseAuthentication
  126. app.UseCors("AllowFrontend");
  127. app.UseAuthentication();
  128. app.UseAuthorization();
  129. app.MapStaticAssets();
  130. app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}")
  131. .WithStaticAssets();
  132. app.MapControllers();
  133. app.Run();