Startup.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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.Http;
  17. using Microsoft.AspNetCore.HttpOverrides;
  18. using Microsoft.Extensions.DependencyInjection;
  19. using Microsoft.Extensions.Hosting;
  20. using Newtonsoft.Json;
  21. using OnceMi.AspNetCore.OSS;
  22. using SixLabors.ImageSharp.Web.DependencyInjection;
  23. using System;
  24. namespace Admin.NET.Web.Core;
  25. public class Startup : AppStartup
  26. {
  27. public void ConfigureServices(IServiceCollection services)
  28. {
  29. // 配置选项
  30. services.AddProjectOptions();
  31. // 缓存注册
  32. services.AddCache();
  33. // SqlSugar
  34. services.AddSqlSugar();
  35. // JWT
  36. services.AddJwt<JwtHandler>(enableGlobalAuthorize: true)
  37. // 添加 Signature 身份验证
  38. .AddSignatureAuthentication(options =>
  39. {
  40. options.Events = SysOpenAccessService.GetSignatureAuthenticationEventImpl();
  41. });
  42. // 允许跨域
  43. services.AddCorsAccessor();
  44. // 远程请求
  45. services.AddRemoteRequest();
  46. // 任务队列
  47. services.AddTaskQueue();
  48. // 任务调度
  49. services.AddSchedule(options =>
  50. {
  51. options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
  52. options.AddMonitor<JobMonitor>(); // 添加作业执行监视器
  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.GetRequiredService<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.Append("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(options =>
  194. {
  195. options.RequestPath = "/schedule"; // 必须以 / 开头且不以 / 结尾
  196. options.DisableOnProduction = true; // 生产环境关闭
  197. options.DisplayEmptyTriggerJobs = true; // 是否显示空作业触发器的作业
  198. options.DisplayHead = false; // 是否显示页头
  199. options.DefaultExpandAllJobs = false; // 是否默认展开所有作业
  200. });
  201. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  202. app.UseKnife4UI(options =>
  203. {
  204. options.RoutePrefix = "kapi";
  205. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  206. {
  207. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  208. }
  209. });
  210. app.UseInject(string.Empty, options =>
  211. {
  212. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  213. {
  214. groupInfo.Description += "<br/><u><b><font color='FF0000'> 👮不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!</font></b></u>";
  215. }
  216. });
  217. app.UseEndpoints(endpoints =>
  218. {
  219. // 注册集线器
  220. endpoints.MapHubs();
  221. endpoints.MapControllerRoute(
  222. name: "default",
  223. pattern: "{controller=Home}/{action=Index}/{id?}");
  224. });
  225. }
  226. }