Startup.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // 大名科技(天津)有限公司 版权所有
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动
  6. //
  7. // 任何基于本项目二次开发而产生的一切法律纠纷和责任,均与作者无关
  8. using Admin.NET.Core;
  9. using Admin.NET.Core.Service;
  10. using AspNetCoreRateLimit;
  11. using Furion;
  12. using Furion.SpecificationDocument;
  13. using Furion.VirtualFileServer;
  14. using IGeekFan.AspNetCore.Knife4jUI;
  15. using IPTools.Core;
  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. #region Redis消息队列
  101. //// 替换事件源存储器
  102. //options.ReplaceStorer(serviceProvider =>
  103. //{
  104. // var redisCache = serviceProvider.GetService<ICache>();
  105. // // 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  106. // return new RedisEventSourceStorer(redisCache, "adminnet", 3000);
  107. //});
  108. #endregion Redis消息队列
  109. #region RabbitMQ消息队列
  110. //// 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  111. //var eventBusOpt = App.GetConfig<EventBusOptions>("EventBus", true);
  112. //var rbmqEventSourceStorer = new RabbitMQEventSourceStore(new ConnectionFactory
  113. //{
  114. // UserName = eventBusOpt.RabbitMQ.UserName,
  115. // Password = eventBusOpt.RabbitMQ.Password,
  116. // HostName = eventBusOpt.RabbitMQ.HostName,
  117. // Port = eventBusOpt.RabbitMQ.Port
  118. //}, "adminnet", 3000);
  119. //// 替换默认事件总线存储器
  120. //options.ReplaceStorer(serviceProvider =>
  121. //{
  122. // return rbmqEventSourceStorer;
  123. //});
  124. #endregion RabbitMQ消息队列
  125. });
  126. // 图像处理
  127. services.AddImageSharp();
  128. // OSS对象存储
  129. var ossOpt = App.GetConfig<OSSProviderOptions>("OSSProvider", true);
  130. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  131. // 模板引擎
  132. services.AddViewEngine();
  133. // 即时通讯
  134. services.AddSignalR(SetNewtonsoftJsonSetting);
  135. //services.AddSingleton<IUserIdProvider, UserIdProvider>();
  136. // 系统日志
  137. services.AddLoggingSetup();
  138. // 验证码
  139. services.AddCaptcha();
  140. // 控制台logo
  141. services.AddConsoleLogo();
  142. // 将IP地址数据库文件完全加载到内存,提升查询速度(以空间换时间,内存将会增加60-70M)
  143. IpToolSettings.LoadInternationalDbToMemory = true;
  144. // 设置默认查询器China和International
  145. //IpToolSettings.DefalutSearcherType = IpSearcherType.China;
  146. IpToolSettings.DefalutSearcherType = IpSearcherType.International;
  147. }
  148. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  149. {
  150. app.UseForwardedHeaders();
  151. if (env.IsDevelopment())
  152. {
  153. app.UseDeveloperExceptionPage();
  154. }
  155. else
  156. {
  157. app.UseExceptionHandler("/Home/Error");
  158. app.UseHsts();
  159. }
  160. app.Use(async (context, next) =>
  161. {
  162. context.Response.Headers.Add("Admin.NET", "Admin.NET");
  163. await next();
  164. });
  165. // 图像处理
  166. app.UseImageSharp();
  167. // 特定文件类型(文件后缀)处理
  168. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  169. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  170. app.UseStaticFiles(new StaticFileOptions
  171. {
  172. ContentTypeProvider = contentTypeProvider
  173. });
  174. //// 启用HTTPS
  175. //app.UseHttpsRedirection();
  176. // 启用OAuth
  177. app.UseOAuth();
  178. // 添加状态码拦截中间件
  179. app.UseUnifyResultStatusCodes();
  180. // 启用多语言,必须在 UseRouting 之前
  181. app.UseAppLocalization();
  182. // 路由注册
  183. app.UseRouting();
  184. // 启用跨域,必须在 UseRouting 和 UseAuthentication 之间注册
  185. app.UseCorsAccessor();
  186. // 启用鉴权授权
  187. app.UseAuthentication();
  188. app.UseAuthorization();
  189. // 限流组件(在跨域之后)
  190. app.UseIpRateLimiting();
  191. app.UseClientRateLimiting();
  192. // 任务调度看板
  193. app.UseScheduleUI();
  194. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  195. app.UseKnife4UI(options =>
  196. {
  197. options.RoutePrefix = "kapi";
  198. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  199. {
  200. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  201. }
  202. });
  203. app.UseInject(string.Empty);
  204. app.UseEndpoints(endpoints =>
  205. {
  206. // 注册集线器
  207. endpoints.MapHubs();
  208. endpoints.MapControllerRoute(
  209. name: "default",
  210. pattern: "{controller=Home}/{action=Index}/{id?}");
  211. });
  212. }
  213. }