Program.cs 4.2 KB

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