Program.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. using AspNetCoreRateLimit;
  2. using Infrastructure.Converter;
  3. using Microsoft.AspNetCore.DataProtection;
  4. using Microsoft.AspNetCore.Localization;
  5. using NLog.Web;
  6. using SqlSugar;
  7. using System.Globalization;
  8. using System.Text.Json;
  9. using ZR.Admin.WebApi.Extensions;
  10. using ZR.Common.Cache;
  11. using ZR.Common.DynamicApiSimple.Extens;
  12. using ZR.Infrastructure.WebExtensions;
  13. using ZR.ServiceCore.Signalr;
  14. using ZR.ServiceCore.SqlSugar;
  15. using ZR.Mall;
  16. //using SQLitePCL;
  17. var builder = WebApplication.CreateBuilder(args);
  18. // NLog: Setup NLog for Dependency injection
  19. //builder.Logging.ClearProviders();
  20. builder.Host.UseNLog();
  21. builder.Services.AddDynamicApi();
  22. // Add services to the container.
  23. builder.Services.AddControllers();
  24. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  25. builder.Services.AddEndpointsApiExplorer();
  26. builder.Services.AddSwaggerGen();
  27. //注入HttpContextAccessor
  28. builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  29. // 跨域配置
  30. builder.Services.AddCors(builder.Configuration);
  31. //消除Error unprotecting the session cookie警告
  32. builder.Services.AddDataProtection()
  33. .PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));
  34. //普通验证码
  35. builder.Services.AddCaptcha(builder.Configuration);
  36. //IPRatelimit
  37. builder.Services.AddIPRate(builder.Configuration);
  38. //builder.Services.AddSession();
  39. builder.Services.AddHttpContextAccessor();
  40. //绑定整个对象到Model上
  41. builder.Services.Configure<OptionsSetting>(builder.Configuration);
  42. builder.Configuration.AddJsonFile("codeGen.json");
  43. builder.Configuration.AddJsonFile("iprate.json");
  44. //jwt 认证
  45. builder.Services.AddJwt();
  46. //配置文件
  47. builder.Services.AddSingleton(new AppSettings(builder.Configuration));
  48. //app服务注册
  49. builder.Services.AddAppService();
  50. //开启计划任务
  51. builder.Services.AddTaskSchedulers();
  52. //请求大小限制
  53. builder.Services.AddRequestLimit(builder.Configuration);
  54. //sqlite 包需要的驱动
  55. //Batteries_V2.Init();
  56. //注册REDIS 服务
  57. var openRedis = builder.Configuration["RedisServer:open"];
  58. if (openRedis == "1")
  59. {
  60. RedisServer.Initalize();
  61. }
  62. builder.Services.AddMvc(options =>
  63. {
  64. options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
  65. })
  66. .AddJsonOptions(options =>
  67. {
  68. //options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
  69. options.JsonSerializerOptions.WriteIndented = true;
  70. options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
  71. options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeNullConverter());
  72. options.JsonSerializerOptions.Converters.Add(new StringConverter());
  73. //PropertyNamingPolicy属性用于前端传过来的属性的格式策略,目前内置的仅有一种策略CamelCase
  74. options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
  75. //options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;//属性可以忽略大小写格式,开启后性能会降低
  76. });
  77. //注入SignalR实时通讯,默认用json传输
  78. builder.Services.AddSignalR()
  79. .AddJsonProtocol(options =>
  80. {
  81. options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
  82. });
  83. builder.Services.AddSwaggerConfig();
  84. // 显示logo
  85. builder.Services.AddLogo();
  86. // 添加本地化服务
  87. builder.Services.AddLocalization(options => options.ResourcesPath = "");
  88. // 在应用程序启动的最开始处调用
  89. var app = builder.Build();
  90. InternalApp.ServiceProvider = app.Services;
  91. InternalApp.Configuration = builder.Configuration;
  92. InternalApp.WebHostEnvironment = app.Environment;
  93. //初始化db
  94. builder.Services.AddDb(app.Environment);
  95. builder.Services.InitDb(app.Environment);
  96. var workId = builder.Configuration["workId"].ParseToInt();
  97. if (app.Environment.IsDevelopment())
  98. {
  99. workId += 1;
  100. }
  101. SnowFlakeSingle.WorkId = workId;
  102. //使用全局异常中间件
  103. app.UseMiddleware<GlobalExceptionMiddleware>();
  104. // 配置中间件以支持本地化
  105. var supportedCultures = new List<CultureInfo> {
  106. new CultureInfo("zh-Hant"),
  107. new CultureInfo("zh-CN"),
  108. new CultureInfo("en")
  109. };
  110. app.UseRequestLocalization(options =>
  111. {
  112. options.DefaultRequestCulture = new RequestCulture("zh-CN");
  113. options.SupportedCultures = supportedCultures;
  114. options.SupportedUICultures = supportedCultures;
  115. options.FallBackToParentCultures = true;
  116. });
  117. //请求头转发
  118. //ForwardedHeaders中间件会自动把反向代理服务器转发过来的X-Forwarded-For(客户端真实IP)以及X-Forwarded-Proto(客户端请求的协议)自动填充到HttpContext.Connection.RemoteIPAddress和HttpContext.Request.Scheme中,这样应用代码中读取到的就是真实的IP和真实的协议了,不需要应用做特殊处理。
  119. app.UseForwardedHeaders(new ForwardedHeadersOptions
  120. {
  121. ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto
  122. });
  123. app.Use((context, next) =>
  124. {
  125. //设置可以多次获取body内容
  126. context.Request.EnableBuffering();
  127. if (context.Request.Query.TryGetValue("access_token", out var token))
  128. {
  129. context.Request.Headers.Append("Authorization", $"Bearer {token}");
  130. }
  131. return next();
  132. });
  133. //开启访问静态文件/wwwroot目录文件,要放在UseRouting前面
  134. app.UseStaticFiles();
  135. //开启路由访问
  136. app.UseRouting();
  137. app.UseCors("Policy");//要放在app.UseEndpoints前。
  138. //app.UseHttpsRedirection();
  139. app.UseAuthentication();
  140. app.UseMiddleware<JwtAuthMiddleware>();
  141. app.UseAuthorization();
  142. //开启缓存
  143. app.UseResponseCaching();
  144. if (builder.Environment.IsProduction())
  145. {
  146. //恢复/启动任务
  147. app.UseAddTaskSchedulers();
  148. }
  149. //初始化字典数据
  150. app.UseInit();
  151. //swagger 只在开发环境中使用
  152. if (builder.Environment.IsDevelopment())
  153. {
  154. app.UseSwagger();
  155. }
  156. //启用客户端IP限制速率
  157. app.UseIpRateLimiting();
  158. app.UseRateLimiter();
  159. //设置socket连接
  160. app.MapHub<MessageHub>("/msgHub");
  161. app.MapControllerRoute(
  162. name: "default",
  163. pattern: "{controller=Home}/{action=Index}/{id?}");
  164. app.MapControllers();
  165. app.Run();