Startup.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. #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. }
  143. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  144. {
  145. if (env.IsDevelopment())
  146. {
  147. app.UseDeveloperExceptionPage();
  148. app.UseForwardedHeaders();
  149. }
  150. else
  151. {
  152. app.UseExceptionHandler("/Home/Error");
  153. app.UseForwardedHeaders();
  154. app.UseHsts();
  155. }
  156. // 图像处理
  157. app.UseImageSharp();
  158. // 特定文件类型(文件后缀)处理
  159. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  160. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  161. app.UseStaticFiles(new StaticFileOptions
  162. {
  163. ContentTypeProvider = contentTypeProvider
  164. });
  165. //// 启用HTTPS
  166. //app.UseHttpsRedirection();
  167. // 启用OAuth
  168. app.UseOAuth();
  169. // 添加状态码拦截中间件
  170. app.UseUnifyResultStatusCodes();
  171. // 启用多语言,必须在 UseRouting 之前
  172. app.UseAppLocalization();
  173. // 路由注册
  174. app.UseRouting();
  175. // 启用跨域,必须在 UseRouting 和 UseAuthentication 之间注册
  176. app.UseCorsAccessor();
  177. // 启用鉴权授权
  178. app.UseAuthentication();
  179. app.UseAuthorization();
  180. // 限流组件(在跨域之后)
  181. app.UseIpRateLimiting();
  182. app.UseClientRateLimiting();
  183. // 任务调度看板
  184. app.UseScheduleUI();
  185. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  186. app.UseKnife4UI(options =>
  187. {
  188. options.RoutePrefix = "kapi";
  189. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  190. {
  191. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  192. }
  193. });
  194. app.UseInject(string.Empty);
  195. app.UseEndpoints(endpoints =>
  196. {
  197. // 注册集线器
  198. endpoints.MapHubs();
  199. endpoints.MapControllerRoute(
  200. name: "default",
  201. pattern: "{controller=Home}/{action=Index}/{id?}");
  202. });
  203. }
  204. }