Startup.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Admin.NET.Core;
  7. using Admin.NET.Core.Service;
  8. using AspNetCoreRateLimit;
  9. using Furion;
  10. using Furion.SpecificationDocument;
  11. using Furion.VirtualFileServer;
  12. using IGeekFan.AspNetCore.Knife4jUI;
  13. using IPTools.Core;
  14. using Microsoft.AspNetCore.Builder;
  15. using Microsoft.AspNetCore.Hosting;
  16. using Microsoft.AspNetCore.HttpOverrides;
  17. using Microsoft.Extensions.DependencyInjection;
  18. using Microsoft.Extensions.Hosting;
  19. using Newtonsoft.Json;
  20. using OnceMi.AspNetCore.OSS;
  21. using SixLabors.ImageSharp.Web.DependencyInjection;
  22. using System;
  23. namespace Admin.NET.Web.Core;
  24. public class Startup : AppStartup
  25. {
  26. public void ConfigureServices(IServiceCollection services)
  27. {
  28. // 配置选项
  29. services.AddProjectOptions();
  30. // 缓存注册
  31. services.AddCache();
  32. // SqlSugar
  33. services.AddSqlSugar();
  34. // JWT
  35. services.AddJwt<JwtHandler>(enableGlobalAuthorize: true)
  36. // 添加 Signature 身份验证
  37. .AddSignatureAuthentication(options =>
  38. {
  39. options.Events = SysOpenAccessService.GetSignatureAuthenticationEventImpl();
  40. });
  41. // 允许跨域
  42. services.AddCorsAccessor();
  43. // 远程请求
  44. services.AddRemoteRequest();
  45. // 任务队列
  46. services.AddTaskQueue();
  47. // 任务调度
  48. services.AddSchedule(options =>
  49. {
  50. options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
  51. });
  52. // 脱敏检测
  53. services.AddSensitiveDetection();
  54. // Json序列化设置
  55. static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
  56. {
  57. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  58. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  59. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  60. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  61. // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
  62. // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
  63. // setting.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过17位开启
  64. // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
  65. // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
  66. // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
  67. };
  68. services.AddControllersWithViews()
  69. .AddAppLocalization()
  70. .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
  71. //.AddXmlSerializerFormatters()
  72. //.AddXmlDataContractSerializerFormatters()
  73. .AddInjectWithUnifyResult<AdminResultProvider>();
  74. // 三方授权登录OAuth
  75. services.AddOAuth();
  76. // ElasticSearch
  77. services.AddElasticSearch();
  78. // 配置Nginx转发获取客户端真实IP
  79. // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
  80. // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
  81. services.Configure<ForwardedHeadersOptions>(options =>
  82. {
  83. options.ForwardedHeaders = ForwardedHeaders.All;
  84. options.KnownNetworks.Clear();
  85. options.KnownProxies.Clear();
  86. });
  87. // 限流服务
  88. services.AddInMemoryRateLimiting();
  89. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  90. // 事件总线
  91. services.AddEventBus(options =>
  92. {
  93. options.UseUtcTimestamp = false;
  94. // 不启用事件日志
  95. options.LogEnabled = false;
  96. // 事件执行器(失败重试)
  97. options.AddExecutor<RetryEventHandlerExecutor>();
  98. #region Redis消息队列
  99. //// 替换事件源存储器
  100. //options.ReplaceStorer(serviceProvider =>
  101. //{
  102. // var redisCache = serviceProvider.GetRequiredService<ICache>();
  103. // // 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  104. // return new RedisEventSourceStorer(redisCache, "adminnet", 3000);
  105. //});
  106. #endregion Redis消息队列
  107. #region RabbitMQ消息队列
  108. //// 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  109. //var eventBusOpt = App.GetConfig<EventBusOptions>("EventBus", true);
  110. //var rbmqEventSourceStorer = new RabbitMQEventSourceStore(new ConnectionFactory
  111. //{
  112. // UserName = eventBusOpt.RabbitMQ.UserName,
  113. // Password = eventBusOpt.RabbitMQ.Password,
  114. // HostName = eventBusOpt.RabbitMQ.HostName,
  115. // Port = eventBusOpt.RabbitMQ.Port
  116. //}, "adminnet", 3000);
  117. //// 替换默认事件总线存储器
  118. //options.ReplaceStorer(serviceProvider =>
  119. //{
  120. // return rbmqEventSourceStorer;
  121. //});
  122. #endregion RabbitMQ消息队列
  123. });
  124. // 图像处理
  125. services.AddImageSharp();
  126. // OSS对象存储
  127. var ossOpt = App.GetConfig<OSSProviderOptions>("OSSProvider", true);
  128. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  129. // 模板引擎
  130. services.AddViewEngine();
  131. // 即时通讯
  132. services.AddSignalR(SetNewtonsoftJsonSetting);
  133. //services.AddSingleton<IUserIdProvider, UserIdProvider>();
  134. // 系统日志
  135. services.AddLoggingSetup();
  136. // 验证码
  137. services.AddCaptcha();
  138. // 控制台logo
  139. services.AddConsoleLogo();
  140. // 将IP地址数据库文件完全加载到内存,提升查询速度(以空间换时间,内存将会增加60-70M)
  141. IpToolSettings.LoadInternationalDbToMemory = true;
  142. // 设置默认查询器China和International
  143. //IpToolSettings.DefalutSearcherType = IpSearcherType.China;
  144. IpToolSettings.DefalutSearcherType = IpSearcherType.International;
  145. }
  146. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  147. {
  148. app.UseForwardedHeaders();
  149. if (env.IsDevelopment())
  150. {
  151. app.UseDeveloperExceptionPage();
  152. }
  153. else
  154. {
  155. app.UseExceptionHandler("/Home/Error");
  156. app.UseHsts();
  157. }
  158. app.Use(async (context, next) =>
  159. {
  160. context.Response.Headers.Add("Admin.NET", "Admin.NET");
  161. await next();
  162. });
  163. // 图像处理
  164. app.UseImageSharp();
  165. // 特定文件类型(文件后缀)处理
  166. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  167. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  168. app.UseStaticFiles(new StaticFileOptions
  169. {
  170. ContentTypeProvider = contentTypeProvider
  171. });
  172. //// 启用HTTPS
  173. //app.UseHttpsRedirection();
  174. // 启用OAuth
  175. app.UseOAuth();
  176. // 添加状态码拦截中间件
  177. app.UseUnifyResultStatusCodes();
  178. // 启用多语言,必须在 UseRouting 之前
  179. app.UseAppLocalization();
  180. // 路由注册
  181. app.UseRouting();
  182. // 启用跨域,必须在 UseRouting 和 UseAuthentication 之间注册
  183. app.UseCorsAccessor();
  184. // 启用鉴权授权
  185. app.UseAuthentication();
  186. app.UseAuthorization();
  187. // 限流组件(在跨域之后)
  188. app.UseIpRateLimiting();
  189. app.UseClientRateLimiting();
  190. // 任务调度看板
  191. app.UseScheduleUI();
  192. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  193. app.UseKnife4UI(options =>
  194. {
  195. options.RoutePrefix = "kapi";
  196. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  197. {
  198. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  199. }
  200. });
  201. app.UseInject(string.Empty, options =>
  202. {
  203. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  204. {
  205. groupInfo.Description += "<br/><u><b><font color='FF0000'> 👮不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!</font></b></u>";
  206. }
  207. });
  208. app.UseEndpoints(endpoints =>
  209. {
  210. // 注册集线器
  211. endpoints.MapHubs();
  212. endpoints.MapControllerRoute(
  213. name: "default",
  214. pattern: "{controller=Home}/{action=Index}/{id?}");
  215. });
  216. }
  217. }