Program.cs 4.5 KB

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