Startup.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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.Authentication;
  17. using Microsoft.AspNetCore.Authentication.Cookies;
  18. using Microsoft.AspNetCore.Authentication.JwtBearer;
  19. using Microsoft.AspNetCore.Builder;
  20. using Microsoft.AspNetCore.Hosting;
  21. using Microsoft.AspNetCore.HttpOverrides;
  22. using Microsoft.Extensions.DependencyInjection;
  23. using Microsoft.Extensions.Hosting;
  24. using Newtonsoft.Json;
  25. using OnceMi.AspNetCore.OSS;
  26. using StackExchange.Redis;
  27. using System;
  28. using System.Net;
  29. using System.Net.Mail;
  30. using Microsoft.AspNetCore.DataProtection;
  31. using Furion.Logging.Extensions;
  32. using Microsoft.AspNetCore.SignalR;
  33. namespace Admin.NET.Web.Core;
  34. public class Startup : AppStartup
  35. {
  36. public void ConfigureServices(IServiceCollection services)
  37. {
  38. // 配置选项
  39. services.AddProjectOptions();
  40. // 缓存注册
  41. services.AddCache();
  42. // SqlSugar
  43. services.AddSqlSugar();
  44. // JWT
  45. services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
  46. // 允许跨域
  47. services.AddCorsAccessor();
  48. // 远程请求
  49. services.AddRemoteRequest();
  50. // 任务队列
  51. services.AddTaskQueue();
  52. // 任务调度
  53. services.AddSchedule(options =>
  54. {
  55. options.AddPersistence<DbJobPersistence>(); // 添加作业持久化器
  56. });
  57. // 脱敏检测
  58. services.AddSensitiveDetection();
  59. // Json序列化设置
  60. static void SetNewtonsoftJsonSetting(JsonSerializerSettings setting)
  61. {
  62. setting.DateFormatHandling = DateFormatHandling.IsoDateFormat;
  63. setting.DateTimeZoneHandling = DateTimeZoneHandling.Local;
  64. setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
  65. setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
  66. // setting.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 解决动态对象属性名大写
  67. // setting.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
  68. // setting.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过16位开启
  69. // setting.MetadataPropertyHandling = MetadataPropertyHandling.Ignore; // 解决DateTimeOffset异常
  70. // setting.DateParseHandling = DateParseHandling.None; // 解决DateTimeOffset异常
  71. // setting.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }); // 解决DateTimeOffset异常
  72. };
  73. services.AddControllersWithViews()
  74. .AddAppLocalization()
  75. .AddNewtonsoftJson(options => SetNewtonsoftJsonSetting(options.SerializerSettings))
  76. //.AddXmlSerializerFormatters()
  77. //.AddXmlDataContractSerializerFormatters()
  78. .AddInjectWithUnifyResult<AdminResultProvider>();
  79. // 第三方授权登录
  80. var authOpt = App.GetOptions<OAuthOptions>();
  81. services.AddAuthentication(options =>
  82. {
  83. options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  84. options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  85. })
  86. .AddCookie(options =>
  87. {
  88. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.None;
  89. options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
  90. })
  91. .AddWeixin(options =>
  92. {
  93. options.ClientId = authOpt.Weixin?.ClientId;
  94. options.ClientSecret = authOpt.Weixin?.ClientSecret;
  95. })
  96. .AddGitee(options =>
  97. {
  98. options.ClientId = authOpt.Gitee?.ClientId;
  99. options.ClientSecret = authOpt.Gitee?.ClientSecret;
  100. options.ClaimActions.MapJsonKey(OAuthClaim.GiteeAvatarUrl, "avatar_url");
  101. });
  102. // ElasticSearch
  103. services.AddElasticSearch();
  104. // 配置Nginx转发获取客户端真实IP
  105. // 注1:如果负载均衡不是在本机通过 Loopback 地址转发请求的,一定要加上options.KnownNetworks.Clear()和options.KnownProxies.Clear()
  106. // 注2:如果设置环境变量 ASPNETCORE_FORWARDEDHEADERS_ENABLED 为 True,则不需要下面的配置代码
  107. services.Configure<ForwardedHeadersOptions>(options =>
  108. {
  109. options.ForwardedHeaders = ForwardedHeaders.All;
  110. options.KnownNetworks.Clear();
  111. options.KnownProxies.Clear();
  112. });
  113. // 限流服务
  114. services.AddInMemoryRateLimiting();
  115. services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
  116. // 事件总线
  117. services.AddEventBus(options =>
  118. {
  119. options.UseUtcTimestamp = false;
  120. // 不启用事件日志
  121. options.LogEnabled = false;
  122. // 事件执行器(失败重试)
  123. options.AddExecutor<RetryEventHandlerExecutor>();
  124. //// 替换事件源存储器
  125. //options.ReplaceStorer(serviceProvider =>
  126. //{
  127. // var redisCache = serviceProvider.GetService<ICache>();
  128. // // 创建默认内存通道事件源对象,可自定义队列路由key,比如这里是 eventbus
  129. // return new RedisEventSourceStorer(redisCache, "eventbus", 3000);
  130. //});
  131. });
  132. // OSS对象存储
  133. var ossOpt = App.GetOptions<OSSProviderOptions>();
  134. services.AddOSSService(Enum.GetName(ossOpt.Provider), "OSSProvider");
  135. // 电子邮件
  136. var emailOpt = App.GetOptions<EmailOptions>();
  137. services.AddFluentEmail(emailOpt.DefaultFromEmail, emailOpt.DefaultFromName)
  138. .AddSmtpSender(new SmtpClient(emailOpt.Host, emailOpt.Port)
  139. {
  140. EnableSsl = emailOpt.EnableSsl,
  141. UseDefaultCredentials = emailOpt.UseDefaultCredentials,
  142. Credentials = new NetworkCredential(emailOpt.UserName, emailOpt.Password)
  143. });
  144. // 模板引擎
  145. services.AddViewEngine();
  146. // 即时通讯
  147. var signalRBuilder = services.AddSignalR(options =>
  148. {
  149. options.EnableDetailedErrors = true;
  150. options.ClientTimeoutInterval = TimeSpan.FromMinutes(2);
  151. options.KeepAliveInterval = TimeSpan.FromMinutes(1);
  152. }).AddNewtonsoftJsonProtocol(options => SetNewtonsoftJsonSetting(options.PayloadSerializerSettings));
  153. // 若已开启集群配置,则把SignalR配置为支持集群模式
  154. var clusterOpt = App.GetOptions<ClusterOptions>();
  155. if (clusterOpt.Enabled)
  156. {
  157. // StackExchangeRedis 缓存
  158. var redisOptions = App.GetOptions<StackExchangeRedisOptions>();
  159. // 密钥存储(数据保护)
  160. var redisConfig = new ConfigurationOptions
  161. {
  162. AbortOnConnectFail = false,
  163. ServiceName = redisOptions.ServiceName,
  164. AllowAdmin = true,
  165. DefaultDatabase = redisOptions.DefaultDb,
  166. Password = redisOptions.Password
  167. };
  168. redisOptions.EndPoints.ForEach(o => redisConfig.EndPoints.Add(o));
  169. var connection1 = ConnectionMultiplexer.Connect(redisConfig);
  170. services.AddDataProtection()
  171. .PersistKeysToStackExchangeRedis(connection1, "AdminNet:DataProtection-Keys");
  172. signalRBuilder.AddStackExchangeRedis(clusterOpt.SignalR.RedisConfiguration, options =>
  173. {
  174. // 此处设置的ChannelPrefix并不会生效,如果两个不同的项目,且[程序集名+类名]一样,使用同一个redis服务,请注意修改 Hub/OnlineUserHub 的类名。
  175. // 原因请参考下边链接:
  176. // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/RedisHubLifetimeManager.cs#L74
  177. // https://github.com/dotnet/aspnetcore/blob/f9121bc3e976ec40a959818451d126d5126ce868/src/SignalR/server/StackExchangeRedis/src/Internal/RedisChannels.cs#L33
  178. options.Configuration.ChannelPrefix = clusterOpt.SignalR.ChannelPrefix;
  179. options.ConnectionFactory = async writer =>
  180. {
  181. var config = new ConfigurationOptions
  182. {
  183. AbortOnConnectFail = false,
  184. ServiceName = redisOptions.ServiceName,
  185. AllowAdmin = true,
  186. DefaultDatabase = redisOptions.DefaultDb,
  187. Password = redisOptions.Password
  188. };
  189. redisOptions.EndPoints.ForEach(o => config.EndPoints.Add(o));
  190. var connection = await ConnectionMultiplexer.ConnectAsync(config, writer);
  191. connection.ConnectionFailed += (_, e) =>
  192. {
  193. "Connection to Redis failed.".LogError();
  194. };
  195. if (!connection.IsConnected)
  196. {
  197. "Did not connect to Redis.".LogError();
  198. }
  199. return connection;
  200. };
  201. });
  202. }
  203. // 系统日志
  204. services.AddLoggingSetup();
  205. // 验证码
  206. services.AddCaptcha();
  207. // 控制台logo
  208. services.AddConsoleLogo();
  209. }
  210. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  211. {
  212. if (env.IsDevelopment())
  213. {
  214. app.UseDeveloperExceptionPage();
  215. app.UseForwardedHeaders();
  216. }
  217. else
  218. {
  219. app.UseExceptionHandler("/Home/Error");
  220. app.UseForwardedHeaders();
  221. app.UseHsts();
  222. }
  223. // 添加状态码拦截中间件
  224. app.UseUnifyResultStatusCodes();
  225. // 配置多语言
  226. app.UseAppLocalization();
  227. //// 启用HTTPS
  228. //app.UseHttpsRedirection();
  229. // 特定文件类型(文件后缀)处理
  230. var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
  231. // contentTypeProvider.Mappings[".文件后缀"] = "MIME 类型";
  232. app.UseStaticFiles(new StaticFileOptions
  233. {
  234. ContentTypeProvider = contentTypeProvider
  235. });
  236. app.UseRouting();
  237. app.UseCorsAccessor();
  238. // 限流组件(在跨域之后)
  239. app.UseIpRateLimiting();
  240. app.UseClientRateLimiting();
  241. app.UseAuthentication();
  242. app.UseAuthorization();
  243. // 任务调度看板
  244. app.UseScheduleUI();
  245. // 配置Swagger-Knife4UI(路由前缀一致代表独立,不同则代表共存)
  246. app.UseKnife4UI(options =>
  247. {
  248. options.RoutePrefix = "kapi";
  249. foreach (var groupInfo in SpecificationDocumentBuilder.GetOpenApiGroups())
  250. {
  251. options.SwaggerEndpoint("/" + groupInfo.RouteTemplate, groupInfo.Title);
  252. }
  253. });
  254. app.UseInject(string.Empty);
  255. app.UseEndpoints(endpoints =>
  256. {
  257. // 注册集线器
  258. endpoints.MapHubs();
  259. endpoints.MapControllerRoute(
  260. name: "default",
  261. pattern: "{controller=Home}/{action=Index}/{id?}");
  262. });
  263. }
  264. }