Program.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. using DFS.Core.Mvc;
  2. using DFS.Infrastructure.Redis.Extension;
  3. using FreeSql;
  4. using Fuel.Application;
  5. using Fuel.Application.Repositories;
  6. using Fuel.Application.Service;
  7. using Fuel.Infrastructure;
  8. using Fuel.Payment.Service.AliPaymentProcessor.Alipay;
  9. using Fuel.Payment.Service.AllInPayProcessor.AllInPay;
  10. using Fuel.Payment.Service.Factory;
  11. using Fuel.Payment.Service.Pay;
  12. using Fuel.Payment.Service.UnionPayProcessor;
  13. using Fuel.PaymentServer.MicServer;
  14. using Fuel.Infrastructure.Extension;
  15. using CSRedis;
  16. using Microsoft.Extensions.Logging;
  17. using Fuel.Core;
  18. using Microsoft.AspNetCore.Authorization;
  19. using Fuel.Application.Authorization;
  20. using Microsoft.Extensions.DependencyInjection;
  21. using Microsoft.AspNetCore.Authentication.JwtBearer;
  22. using Microsoft.IdentityModel.Tokens;
  23. using System.Text;
  24. using DFS.Core.Mvc.Middlewares;
  25. using Fuel.Payment.Service.WeChatPaymentProcessor.Wechat;
  26. using Fuel.Application.MqttService;
  27. using System.Text.Json;
  28. var builder = WebApplication.CreateBuilder(args);
  29. builder.Services.AddScoped<IPayService, PayService>();
  30. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALI_SCAN", new AlipayPaymentProcessor());
  31. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WX_SCAN", new WechatPaymentProcessor());
  32. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALL_IN_SCAN", new AllInPayProcessor());
  33. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALL_IN_SCAN_V2", new AllInPayProcessorV2());
  34. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WX_ORDER_SCAN", new WechatPaymentProcessor());
  35. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ALI_ORDER_SCAN", new AlipayPaymentProcessor());
  36. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "WECHAT_MINIPROGRAM_PAY", new WechatPaymentProcessor());
  37. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ICBC_SCAN", new IcbcPayProcessor());
  38. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "ICBC_ORDER_SCAN", new IcbcPayProcessor());
  39. //AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "GRG_SCAN", new GrgPayProcessor());
  40. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "UNION_MINI", new MiniUnionPayProcessor());
  41. AsyncPaymentProcessorFactory.Default.Regist(o => o.Channel == "UNION_SCAN", new UnionPayProcessor());
  42. // Add services to the container.
  43. // 添加FreeSQL配置
  44. builder.Services.AddFreeSql(builder.Configuration);
  45. //初始化DFS Server
  46. builder.Services.AddMicService(builder.Environment);
  47. //builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  48. // .AddJwtBearer(options =>
  49. // {
  50. // options.TokenValidationParameters = new TokenValidationParameters
  51. // {
  52. // ValidateIssuer = true,
  53. // ValidateAudience = true,
  54. // ValidateLifetime = true,
  55. // ValidateIssuerSigningKey = true,
  56. // ValidIssuer = ConstKey.JwtIssuer,
  57. // ValidAudience = ConstKey.JwtAudience,
  58. // IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConstKey.JwtKey))
  59. // };
  60. // });
  61. builder.Services.AddHttpContextAccessor();
  62. builder.Services.AddScoped<INozzleRepository, NozzleRepository>();
  63. builder.Services.AddScoped<INozzleService, NozzleService>();
  64. builder.Services.AddScoped<ITransactionsService, TransactionsService>();
  65. builder.Services.AddScoped<IUserService, UserService>();
  66. builder.Services.AddScoped<IApplyService, ApplyService>();
  67. builder.Services.AddScoped<ISiteService, SiteService>();
  68. builder.Services.AddScoped<Authorization>();
  69. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  70. builder.Services.AddEndpointsApiExplorer();
  71. builder.Services.AddSwaggerGen();
  72. builder.Services.AddTransient<IAuthorizationHandler, PermissionHandler>();
  73. Fuel.Infrastructure.Extension.RedisOptions redisOptions = builder.Configuration.GetSection("Redis").Get<Fuel.Infrastructure.Extension.RedisOptions>();
  74. builder.Services.UseRedisClient(redisOptions);
  75. // 动态添加基于权限的策略
  76. void AddPermissionPolicies(AuthorizationOptions options)
  77. {
  78. //var permissions = Authorization.GetPermissions();
  79. //foreach (var permission in permissions)
  80. //{
  81. // options.AddPolicy($"Permission_{permission}", policy =>
  82. // policy.Requirements.Add(new PermissionRequirement(permission)));
  83. //}
  84. using (var scope = builder.Services.BuildServiceProvider().CreateScope())
  85. {
  86. var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
  87. var applyService = scope.ServiceProvider.GetRequiredService<IApplyService>();
  88. var authorization = new Authorization(userService, applyService);
  89. var permissions = authorization.GetPermissions();
  90. foreach (var permission in permissions)
  91. {
  92. options.AddPolicy($"Permission_{permission}", policy =>
  93. policy.Requirements.Add(new PermissionRequirement(permission)));
  94. }
  95. }
  96. }
  97. builder.Services.AddAuthorization(options =>
  98. {
  99. AddPermissionPolicies(options);
  100. });
  101. //mqtt注册
  102. builder.Services.Configure<MqttOptions>(builder.Configuration.GetSection("Mqtt"));
  103. builder.Services.AddScoped<IMqttClientService, MqttClientService>();
  104. builder.Logging.ClearProviders();
  105. // 添加CORS服务,并允许所有来源
  106. builder.Services.AddCors(options =>
  107. {
  108. options.AddPolicy("AllowAll", policy =>
  109. {
  110. policy.AllowAnyOrigin() // 允许所有来源(生产环境应指定具体域名)
  111. .AllowAnyMethod() // 允许所有 HTTP 方法
  112. .AllowAnyHeader() // 允许所有请求头
  113. .SetPreflightMaxAge(TimeSpan.FromSeconds(86400)); // 预检请求缓存时间
  114. });
  115. });
  116. builder.WebHost.ConfigureKestrel(options =>
  117. {
  118. //options.Listen(System.Net.IPAddress.Parse("192.168.0.202"), 5006); // 监听特定IPv4地址的5002端口
  119. //options.Listen(System.Net.IPAddress.Parse("172.31.2.202"), 5006); // 监听特定IPv4地址的5002端口
  120. options.Listen(System.Net.IPAddress.Parse("::1"), 5007); // 监听特定IPv6地址(这里是localhost)的5003端口
  121. });
  122. builder.Services.AddControllers()
  123. .AddJsonOptions(options =>
  124. {
  125. options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; // 支持 camelCase
  126. options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;
  127. });
  128. var app = builder.Build();
  129. app.UseRouting();
  130. app.UseCors("AllowAll");
  131. app.Use(async (context, next) =>
  132. {
  133. context.Response.Headers["Referrer-Policy"] = "strict-origin-when-cross-origin";
  134. context.Request.EnableBuffering(); // 允许多次读取
  135. var requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
  136. Console.WriteLine($"Request Body: {requestBody}");
  137. context.Request.Body.Position = 0; // 重置流的位置
  138. await next();
  139. });
  140. var loggerFactory = LoggerFactory.Create(builder =>
  141. {
  142. builder.AddConsole();
  143. });
  144. var logger = loggerFactory.CreateLogger<DFS.Core.Mvc.Middlewares.SignatureValidator>();
  145. var signatureValidator = new DFS.Core.Mvc.Middlewares.SignatureValidator(logger);
  146. app.UseMiddleware<SignatureValidationMiddleware>(signatureValidator);//签名验证
  147. // 配置HttpRequestReader静态类
  148. var httpContextAccessor = app.Services.GetRequiredService<IHttpContextAccessor>();
  149. HttpRequestReader.Configure(httpContextAccessor);
  150. // Configure the HTTP request pipeline.
  151. if (app.Environment.IsDevelopment())
  152. {
  153. app.UseSwagger();
  154. app.UseSwaggerUI();
  155. }
  156. app.UseDFSServer();
  157. app.UseHttpsRedirection();
  158. app.UseAuthentication();
  159. app.UseAuthorization();
  160. app.MapControllers();
  161. //app.Urls.Add("http://localhost:5006");
  162. app.Run();