Startup.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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 Microsoft.AspNetCore.Builder;
  16. using Microsoft.AspNetCore.Hosting;
  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. });
  53. // 脱敏检测
  54. services.AddSensitiveDetection();
  55. // Json序列化设置
  56. static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
  57. {
  58. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  59. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  60. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  61. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  62. // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
  63. // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
  64. // setting.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过17位开启
  65. // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
  66. // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
  67. // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
  68. };
  69. services.AddControllersWithViews()
  70. .AddAppLocalization()
  71. .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
  72. //.AddXmlSerializerFormatters()
  73. //.AddXmlDataContractSerializerFormatters()
  74. .AddInjectWithUnifyResult<AdminResultProvider>();
  75. // 三方授权登录OAuth
  76. services.AddOAuth();
  77. // ElasticSearch
  78. services.AddElasticSearch();
  79. // 配置Nginx转发获取客户端真实IP
  80. // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
  81. // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
  82. services.Configure<ForwardedHeadersOptions>(options =>
  83. {
  84. options.ForwardedHeaders = ForwardedHeaders.All;
  85. options.KnownNetworks.Clear();
  86. options.KnownProxies.Clear();
  87. });
  88. // 限流服务
  89. services.AddInMemoryRateLimiting();
  90. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  91. // 事件总线
  92. services.AddEventBus(options =>
  93. {
  94. options.UseUtcTimestamp = false;
  95. // 不启用事件日志
  96. options.LogEnabled = false;
  97. // 事件执行器(失败重试)
  98. options.AddExecutor<RetryEventHandlerExecutor>();
  99. #region Redis消息队列
  100. //// 替换事件源存储器
  101. //options.ReplaceStorer(serviceProvider =>
  102. //{
  103. // var redisCache = serviceProvider.GetService<ICache>();
  104. // // 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  105. // return new RedisEventSourceStorer(redisCache, "adminnet", 3000);
  106. //});
  107. #endregion Redis消息队列
  108. #region RabbitMQ消息队列
  109. //// 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  110. //var eventBusOpt = App.GetConfig<EventBusOptions>("EventBus", true);
  111. //var rbmqEventSourceStorer = new RabbitMQEventSourceStore(new ConnectionFactory
  112. //{
  113. // UserName = eventBusOpt.RabbitMQ.UserName,
  114. // Password = eventBusOpt.RabbitMQ.Password,
  115. // HostName = eventBusOpt.RabbitMQ.HostName,
  116. // Port = eventBusOpt.RabbitMQ.Port
  117. //}, "adminnet", 3000);
  118. //// 替换默认事件总线存储器
  119. //options.ReplaceStorer(serviceProvider =>
  120. //{
  121. // return rbmqEventSourceStorer;
  122. //});
  123. #endregion RabbitMQ消息队列
  124. });
  125. // 图像处理
  126. services.AddImageSharp();
  127. // OSS对象存储
  128. var ossOpt = App.GetConfig<OSSProviderOptions>("OSSProvider", true);
  129. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  130. // 模板引擎
  131. services.AddViewEngine();
  132. // 即时通讯
  133. services.AddSignalR(SetNewtonsoftJsonSetting);
  134. //services.AddSingleton<IUserIdProvider, UserIdProvider>();
  135. // 系统日志
  136. services.AddLoggingSetup();
  137. // 验证码
  138. services.AddCaptcha();
  139. // 控制台logo
  140. services.AddConsoleLogo();
  141. }
  142. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  143. {
  144. app.UseForwardedHeaders();
  145. if (env.IsDevelopment())
  146. {
  147. app.UseDeveloperExceptionPage();
  148. }
  149. else
  150. {
  151. app.UseExceptionHandler("/Home/Error");
  152. app.UseHsts();
  153. }
  154. app.Use(async (context, next) =>
  155. {
  156. context.Response.Headers.Add("Admin.NET", "Admin.NET");
  157. await next();
  158. });
  159. // 图像处理
  160. app.UseImageSharp();
  161. // 特定文件类型(文件后缀)处理
  162. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  163. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  164. app.UseStaticFiles(new StaticFileOptions
  165. {
  166. ContentTypeProvider = contentTypeProvider
  167. });
  168. //// 启用HTTPS
  169. //app.UseHttpsRedirection();
  170. // 启用OAuth
  171. app.UseOAuth();
  172. // 添加状态码拦截中间件
  173. app.UseUnifyResultStatusCodes();
  174. // 启用多语言,必须在 UseRouting 之前
  175. app.UseAppLocalization();
  176. // 路由注册
  177. app.UseRouting();
  178. // 启用跨域,必须在 UseRouting 和 UseAuthentication 之间注册
  179. app.UseCorsAccessor();
  180. // 启用鉴权授权
  181. app.UseAuthentication();
  182. app.UseAuthorization();
  183. // 限流组件(在跨域之后)
  184. app.UseIpRateLimiting();
  185. app.UseClientRateLimiting();
  186. // 任务调度看板
  187. app.UseScheduleUI();
  188. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  189. app.UseKnife4UI(options =>
  190. {
  191. options.RoutePrefix = "kapi";
  192. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  193. {
  194. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  195. }
  196. });
  197. app.UseInject(string.Empty);
  198. app.UseEndpoints(endpoints =>
  199. {
  200. // 注册集线器
  201. endpoints.MapHubs();
  202. endpoints.MapControllerRoute(
  203. name: "default",
  204. pattern: "{controller=Home}/{action=Index}/{id?}");
  205. });
  206. }
  207. }