Startup.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using Admin.NET.Core;
  10. using Admin.NET.Core.Service;
  11. using AspNetCoreRateLimit;
  12. using Furion;
  13. using Furion.SpecificationDocument;
  14. using Furion.VirtualFileServer;
  15. using IGeekFan.AspNetCore.Knife4jUI;
  16. using Microsoft.AspNetCore.Builder;
  17. using Microsoft.AspNetCore.Hosting;
  18. using Microsoft.AspNetCore.HttpOverrides;
  19. using Microsoft.Extensions.DependencyInjection;
  20. using Microsoft.Extensions.Hosting;
  21. using Newtonsoft.Json;
  22. using OnceMi.AspNetCore.OSS;
  23. using SixLabors.ImageSharp.Web.DependencyInjection;
  24. using System;
  25. namespace Admin.NET.Web.Core;
  26. public class Startup : AppStartup
  27. {
  28. public void ConfigureServices(IServiceCollection services)
  29. {
  30. // 配置选项
  31. services.AddProjectOptions();
  32. // 缓存注册
  33. services.AddCache();
  34. // SqlSugar
  35. services.AddSqlSugar();
  36. // JWT
  37. services.AddJwt<JwtHandler>(enableGlobalAuthorize: true)
  38. // 添加 Signature 身份验证
  39. .AddSignatureAuthentication(options =>
  40. {
  41. options.Events = SysOpenAccessService.GetSignatureAuthenticationEventImpl();
  42. });
  43. // 允许跨域
  44. services.AddCorsAccessor();
  45. // 远程请求
  46. services.AddRemoteRequest();
  47. // 任务队列
  48. services.AddTaskQueue();
  49. // 任务调度
  50. services.AddSchedule(options =>
  51. {
  52. options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
  53. });
  54. // 脱敏检测
  55. services.AddSensitiveDetection();
  56. // Json序列化设置
  57. static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
  58. {
  59. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  60. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  61. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  62. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  63. // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
  64. // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
  65. // setting.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过17位开启
  66. // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
  67. // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
  68. // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
  69. };
  70. services.AddControllersWithViews()
  71. .AddAppLocalization()
  72. .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
  73. //.AddXmlSerializerFormatters()
  74. //.AddXmlDataContractSerializerFormatters()
  75. .AddInjectWithUnifyResult<AdminResultProvider>();
  76. // 三方授权登录OAuth
  77. services.AddOAuth();
  78. // ElasticSearch
  79. services.AddElasticSearch();
  80. // 配置Nginx转发获取客户端真实IP
  81. // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
  82. // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
  83. services.Configure<ForwardedHeadersOptions>(options =>
  84. {
  85. options.ForwardedHeaders = ForwardedHeaders.All;
  86. options.KnownNetworks.Clear();
  87. options.KnownProxies.Clear();
  88. });
  89. // 限流服务
  90. services.AddInMemoryRateLimiting();
  91. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  92. // 事件总线
  93. services.AddEventBus(options =>
  94. {
  95. options.UseUtcTimestamp = false;
  96. // 不启用事件日志
  97. options.LogEnabled = false;
  98. // 事件执行器(失败重试)
  99. options.AddExecutor<RetryEventHandlerExecutor>();
  100. //// 替换事件源存储器
  101. //options.ReplaceStorer(serviceProvider =>
  102. //{
  103. // var redisCache = serviceProvider.GetService<ICache>();
  104. // // 创建默认内存通道事件源对象,可自定义队列路由key,比如这里是 eventbus
  105. // return new RedisEventSourceStorer(redisCache, "eventbus", 3000);
  106. //});
  107. });
  108. // 图像处理
  109. services.AddImageSharp();
  110. // OSS对象存储
  111. var ossOpt = App.GetConfig<OSSProviderOptions>("OSSProvider", true);
  112. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  113. // 模板引擎
  114. services.AddViewEngine();
  115. // 即时通讯
  116. services.AddSignalR(SetNewtonsoftJsonSetting);
  117. //services.AddSingleton<IUserIdProvider, UserIdProvider>();
  118. // 系统日志
  119. services.AddLoggingSetup();
  120. // 验证码
  121. services.AddCaptcha();
  122. // 控制台logo
  123. services.AddConsoleLogo();
  124. }
  125. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  126. {
  127. if (env.IsDevelopment())
  128. {
  129. app.UseDeveloperExceptionPage();
  130. app.UseForwardedHeaders();
  131. }
  132. else
  133. {
  134. app.UseExceptionHandler("/Home/Error");
  135. app.UseForwardedHeaders();
  136. app.UseHsts();
  137. }
  138. //// 启用HTTPS
  139. //app.UseHttpsRedirection();
  140. // 启用跨域
  141. app.UseCorsAccessor();
  142. // 启用鉴权授权
  143. app.UseAuthentication();
  144. app.UseAuthorization();
  145. // 启用多语言,必须在路由注册之前
  146. app.UseAppLocalization();
  147. // 特定文件类型(文件后缀)处理
  148. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  149. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  150. app.UseStaticFiles(new StaticFileOptions
  151. {
  152. ContentTypeProvider = contentTypeProvider
  153. });
  154. // 路由注册
  155. app.UseRouting();
  156. // 添加状态码拦截中间件
  157. app.UseUnifyResultStatusCodes();
  158. // 图像处理
  159. app.UseImageSharp();
  160. // 限流组件(在跨域之后)
  161. app.UseIpRateLimiting();
  162. app.UseClientRateLimiting();
  163. // 任务调度看板
  164. app.UseScheduleUI();
  165. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  166. app.UseKnife4UI(options =>
  167. {
  168. options.RoutePrefix = "kapi";
  169. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  170. {
  171. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  172. }
  173. });
  174. app.UseInject(string.Empty);
  175. app.UseEndpoints(endpoints =>
  176. {
  177. // 注册集线器
  178. endpoints.MapHubs();
  179. endpoints.MapControllerRoute(
  180. name: "default",
  181. pattern: "{controller=Home}/{action=Index}/{id?}");
  182. });
  183. }
  184. }