Startup.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // 大名科技(天津)有限公司版权所有 电话:18020030720 QQ:515096995
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. using Admin.NET.Core;
  5. using Admin.NET.Core.Service;
  6. using AspNetCoreRateLimit;
  7. using Furion;
  8. using Furion.SpecificationDocument;
  9. using Furion.VirtualFileServer;
  10. using IGeekFan.AspNetCore.Knife4jUI;
  11. using Microsoft.AspNetCore.Builder;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.AspNetCore.HttpOverrides;
  14. using Microsoft.Extensions.DependencyInjection;
  15. using Microsoft.Extensions.Hosting;
  16. using Newtonsoft.Json;
  17. using OnceMi.AspNetCore.OSS;
  18. using SixLabors.ImageSharp.Web.DependencyInjection;
  19. using System;
  20. namespace Admin.NET.Web.Core;
  21. public class Startup : AppStartup
  22. {
  23. public void ConfigureServices(IServiceCollection services)
  24. {
  25. // 配置选项
  26. services.AddProjectOptions();
  27. // 缓存注册
  28. services.AddCache();
  29. // SqlSugar
  30. services.AddSqlSugar();
  31. // JWT
  32. services.AddJwt<JwtHandler>(enableGlobalAuthorize: true)
  33. // 添加 Signature 身份验证
  34. .AddSignatureAuthentication(options =>
  35. {
  36. options.Events = SysOpenAccessService.GetSignatureAuthenticationEventImpl();
  37. });
  38. // 允许跨域
  39. services.AddCorsAccessor();
  40. // 远程请求
  41. services.AddRemoteRequest();
  42. // 任务队列
  43. services.AddTaskQueue();
  44. // 任务调度
  45. services.AddSchedule(options =>
  46. {
  47. options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
  48. });
  49. // 脱敏检测
  50. services.AddSensitiveDetection();
  51. // Json序列化设置
  52. static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
  53. {
  54. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  55. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  56. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  57. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  58. // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
  59. // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
  60. // setting.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过17位开启
  61. // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
  62. // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
  63. // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
  64. };
  65. services.AddControllersWithViews()
  66. .AddAppLocalization()
  67. .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
  68. //.AddXmlSerializerFormatters()
  69. //.AddXmlDataContractSerializerFormatters()
  70. .AddInjectWithUnifyResult<AdminResultProvider>();
  71. // 三方授权登录OAuth
  72. services.AddOAuth();
  73. // ElasticSearch
  74. services.AddElasticSearch();
  75. // 配置Nginx转发获取客户端真实IP
  76. // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
  77. // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
  78. services.Configure<ForwardedHeadersOptions>(options =>
  79. {
  80. options.ForwardedHeaders = ForwardedHeaders.All;
  81. options.KnownNetworks.Clear();
  82. options.KnownProxies.Clear();
  83. });
  84. // 限流服务
  85. services.AddInMemoryRateLimiting();
  86. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  87. // 事件总线
  88. services.AddEventBus(options =>
  89. {
  90. options.UseUtcTimestamp = false;
  91. // 不启用事件日志
  92. options.LogEnabled = false;
  93. // 事件执行器(失败重试)
  94. options.AddExecutor<RetryEventHandlerExecutor>();
  95. #region Redis消息队列
  96. //// 替换事件源存储器
  97. //options.ReplaceStorer(serviceProvider =>
  98. //{
  99. // var redisCache = serviceProvider.GetService<ICache>();
  100. // // 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  101. // return new RedisEventSourceStorer(redisCache, "adminnet", 3000);
  102. //});
  103. #endregion Redis消息队列
  104. #region RabbitMQ消息队列
  105. //// 创建默认内存通道事件源对象,可自定义队列路由key,如:adminnet
  106. //var eventBusOpt = App.GetConfig<EventBusOptions>("EventBus", true);
  107. //var rbmqEventSourceStorer = new RabbitMQEventSourceStore(new ConnectionFactory
  108. //{
  109. // UserName = eventBusOpt.RabbitMQ.UserName,
  110. // Password = eventBusOpt.RabbitMQ.Password,
  111. // HostName = eventBusOpt.RabbitMQ.HostName,
  112. // Port = eventBusOpt.RabbitMQ.Port
  113. //}, "adminnet", 3000);
  114. //// 替换默认事件总线存储器
  115. //options.ReplaceStorer(serviceProvider =>
  116. //{
  117. // return rbmqEventSourceStorer;
  118. //});
  119. #endregion RabbitMQ消息队列
  120. });
  121. // 图像处理
  122. services.AddImageSharp();
  123. // OSS对象存储
  124. var ossOpt = App.GetConfig<OSSProviderOptions>("OSSProvider", true);
  125. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  126. // 模板引擎
  127. services.AddViewEngine();
  128. // 即时通讯
  129. services.AddSignalR(SetNewtonsoftJsonSetting);
  130. //services.AddSingleton<IUserIdProvider, UserIdProvider>();
  131. // 系统日志
  132. services.AddLoggingSetup();
  133. // 验证码
  134. services.AddCaptcha();
  135. // 控制台logo
  136. services.AddConsoleLogo();
  137. }
  138. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  139. {
  140. if (env.IsDevelopment())
  141. {
  142. app.UseDeveloperExceptionPage();
  143. app.UseForwardedHeaders();
  144. }
  145. else
  146. {
  147. app.UseExceptionHandler("/Home/Error");
  148. app.UseForwardedHeaders();
  149. app.UseHsts();
  150. }
  151. app.Use(async (context, next) =>
  152. {
  153. context.Response.Headers.Add("Admin.NET", "Admin.NET");
  154. await next();
  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. }