Startup.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. using Autofac;
  2. using Autofac.Extensions.DependencyInjection;
  3. using CSRedis;
  4. using Hangfire;
  5. using Hangfire.Dashboard;
  6. using Hangfire.MemoryStorage;
  7. using JiebaNet.Segmenter;
  8. using Masuit.LuceneEFCore.SearchEngine;
  9. using Masuit.LuceneEFCore.SearchEngine.Extensions;
  10. using Masuit.MyBlogs.Core.Common;
  11. using Masuit.MyBlogs.Core.Configs;
  12. using Masuit.MyBlogs.Core.Extensions;
  13. using Masuit.MyBlogs.Core.Extensions.Hangfire;
  14. using Masuit.MyBlogs.Core.Hubs;
  15. using Masuit.MyBlogs.Core.Infrastructure;
  16. using Masuit.MyBlogs.Core.Models.DTO;
  17. using Masuit.MyBlogs.Core.Models.ViewModel;
  18. using Masuit.Tools;
  19. using Masuit.Tools.AspNetCore.Mime;
  20. using Masuit.Tools.Core.AspNetCore;
  21. using Masuit.Tools.Core.Config;
  22. using Masuit.Tools.Core.Net;
  23. using Masuit.Tools.Systems;
  24. using Microsoft.AspNetCore.Builder;
  25. using Microsoft.AspNetCore.Http;
  26. using Microsoft.AspNetCore.Http.Features;
  27. using Microsoft.AspNetCore.HttpOverrides;
  28. using Microsoft.AspNetCore.Rewrite;
  29. using Microsoft.AspNetCore.StaticFiles;
  30. using Microsoft.AspNetCore.WebSockets;
  31. using Microsoft.EntityFrameworkCore;
  32. using Microsoft.Extensions.Configuration;
  33. using Microsoft.Extensions.DependencyInjection;
  34. using Microsoft.Extensions.Hosting;
  35. using Microsoft.Extensions.Primitives;
  36. using Microsoft.Net.Http.Headers;
  37. using StackExchange.Profiling;
  38. using System;
  39. using System.IO;
  40. using System.Linq;
  41. using System.Net.Http;
  42. using System.Threading.Tasks;
  43. using IWebHostEnvironment = Microsoft.AspNetCore.Hosting.IWebHostEnvironment;
  44. using SameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode;
  45. namespace Masuit.MyBlogs.Core
  46. {
  47. /// <summary>
  48. /// asp.net core核心配置
  49. /// </summary>
  50. public class Startup
  51. {
  52. /// <summary>
  53. /// 依赖注入容器
  54. /// </summary>
  55. public static IServiceProvider ServiceProvider { get; private set; }
  56. /// <summary>
  57. /// 配置中心
  58. /// </summary>
  59. public IConfiguration Configuration { get; set; }
  60. private readonly IWebHostEnvironment _env;
  61. /// <summary>
  62. /// asp.net core核心配置
  63. /// </summary>
  64. /// <param name="configuration"></param>
  65. public Startup(IConfiguration configuration, IWebHostEnvironment env)
  66. {
  67. _env = env;
  68. void BindConfig()
  69. {
  70. Configuration = configuration;
  71. AppConfig.ConnString = configuration[nameof(AppConfig.ConnString)];
  72. AppConfig.BaiduAK = configuration[nameof(AppConfig.BaiduAK)];
  73. AppConfig.Redis = configuration[nameof(AppConfig.Redis)];
  74. AppConfig.TrueClientIPHeader = configuration[nameof(AppConfig.TrueClientIPHeader)] ?? "CF-Connecting-IP";
  75. AppConfig.EnableIPDirect = bool.Parse(configuration[nameof(AppConfig.EnableIPDirect)] ?? "false");
  76. configuration.Bind("Imgbed:AliyunOSS", AppConfig.AliOssConfig);
  77. configuration.Bind("Imgbed:Gitlabs", AppConfig.GitlabConfigs);
  78. configuration.AddToMasuitTools();
  79. }
  80. ChangeToken.OnChange(configuration.GetReloadToken, BindConfig);
  81. BindConfig();
  82. }
  83. /// <summary>
  84. /// ConfigureServices
  85. /// </summary>
  86. /// <param name="services"></param>
  87. /// <returns></returns>
  88. public void ConfigureServices(IServiceCollection services)
  89. {
  90. RedisHelper.Initialization(new CSRedisClient(AppConfig.Redis));
  91. services.Configure<CookiePolicyOptions>(options =>
  92. {
  93. options.MinimumSameSitePolicy = SameSiteMode.None;
  94. }); //配置Cookie策略
  95. services.AddDbContext<DataContext>(opt =>
  96. {
  97. opt.UseMySql(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(3)).EnableDetailedErrors().EnableSensitiveDataLogging();
  98. //opt.UseSqlServer(AppConfig.ConnString);
  99. }); //配置数据库
  100. services.Configure<FormOptions>(options =>
  101. {
  102. options.MultipartBodyLengthLimit = 104857600; // 100MB
  103. }); //配置请求长度
  104. services.AddSession().AddAntiforgery(); //注入Session
  105. services.AddWebSockets(opt => opt.ReceiveBufferSize = 4096 * 1024).AddSignalR().AddNewtonsoftJsonProtocol();
  106. services.AddHttpsRedirection(options =>
  107. {
  108. options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
  109. });
  110. services.AddResponseCache().AddCacheConfig();
  111. services.AddHangfire((provider, configuration) =>
  112. {
  113. configuration.UseFilter(new AutomaticRetryAttribute());
  114. configuration.UseMemoryStorage();
  115. }); //配置hangfire
  116. services.AddSevenZipCompressor().AddResumeFileResult().AddSearchEngine<DataContext>(new LuceneIndexerOptions()
  117. {
  118. Path = "lucene"
  119. }); // 配置7z和断点续传和Redis和Lucene搜索引擎
  120. services.AddHttpClient("", c => c.Timeout = TimeSpan.FromSeconds(30)).ConfigurePrimaryHttpMessageHandler(provider => new HttpClientHandler
  121. {
  122. ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
  123. }); //注入HttpClient
  124. services.AddHttpClient<ImagebedClient>();
  125. services.AddHttpContextAccessor(); //注入静态HttpContext
  126. services.AddMiniProfiler(options =>
  127. {
  128. options.RouteBasePath = "/profiler";
  129. options.EnableServerTimingHeader = true;
  130. options.ResultsAuthorize = req => req.HttpContext.Session.Get<UserInfoDto>(SessionKey.UserInfo)?.IsAdmin ?? false;
  131. options.ResultsListAuthorize = options.ResultsAuthorize;
  132. options.IgnoredPaths.AddRange("/Assets/", "/Content/", "/fonts/", "/images/", "/ng-views/", "/Scripts/", "/static/", "/template/", "/cloud10.png", "/favicon.ico");
  133. options.PopupRenderPosition = RenderPosition.BottomLeft;
  134. options.PopupShowTimeWithChildren = true;
  135. options.PopupShowTrivial = true;
  136. }).AddEntityFramework();
  137. services.AddBundling().UseDefaults(_env).UseNUglify().EnableMinification().EnableChangeDetection().EnableCacheHeader(TimeSpan.FromHours(1));
  138. switch (Configuration["MailSender"])
  139. {
  140. case "Mailgun":
  141. services.AddHttpClient<IMailSender, MailgunSender>();
  142. break;
  143. default:
  144. services.AddSingleton<IMailSender, SmtpSender>();
  145. break;
  146. }
  147. services.AddMapper().AddAutofac().AddMyMvc().Configure<ForwardedHeadersOptions>(options => // X-Forwarded-For
  148. {
  149. options.ForwardLimit = null;
  150. options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
  151. options.KnownNetworks.Clear();
  152. options.KnownProxies.Clear();
  153. });
  154. }
  155. public void ConfigureContainer(ContainerBuilder builder)
  156. {
  157. builder.RegisterModule(new AutofacModule());
  158. }
  159. /// <summary>
  160. /// Configure
  161. /// </summary>
  162. /// <param name="app"></param>
  163. /// <param name="env"></param>
  164. /// <param name="db"></param>
  165. /// <param name="hangfire"></param>
  166. /// <param name="luceneIndexerOptions"></param>
  167. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext db, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
  168. {
  169. ServiceProvider = app.ApplicationServices;
  170. app.UseForwardedHeaders().UseCertificateForwarding(); // X-Forwarded-For
  171. if (env.IsDevelopment())
  172. {
  173. app.UseDeveloperExceptionPage();
  174. }
  175. else
  176. {
  177. app.UseExceptionHandler("/ServiceUnavailable");
  178. }
  179. db.Database.EnsureCreated();
  180. InitSettings(db);
  181. app.UseBundles();
  182. UseLuceneSearch(env, hangfire, luceneIndexerOptions);
  183. if (bool.Parse(Configuration["Https:Enabled"]))
  184. {
  185. app.UseHttpsRedirection();
  186. }
  187. switch (Configuration["UseRewriter"])
  188. {
  189. case "NonWww":
  190. app.UseRewriter(new RewriteOptions().AddRedirectToNonWww()); // URL重写
  191. break;
  192. case "WWW":
  193. app.UseRewriter(new RewriteOptions().AddRedirectToWww(301)); // URL重写
  194. break;
  195. }
  196. app.UseDefaultFiles().UseStaticFiles(new StaticFileOptions //静态资源缓存策略
  197. {
  198. OnPrepareResponse = context =>
  199. {
  200. context.Context.Response.Headers[HeaderNames.CacheControl] = "public,no-cache";
  201. context.Context.Response.Headers[HeaderNames.Expires] = DateTime.Now.AddDays(7).ToString("R");
  202. },
  203. ContentTypeProvider = new FileExtensionContentTypeProvider(MimeMapper.MimeTypes),
  204. });
  205. app.UseSession().UseCookiePolicy().UseMiniProfiler(); //注入Session
  206. app.UseRequestIntercept(); //启用网站请求拦截
  207. app.UseHangfireServer().UseHangfireDashboard("/taskcenter", new DashboardOptions()
  208. {
  209. Authorization = new[]
  210. {
  211. new MyRestrictiveAuthorizationFilter()
  212. }
  213. }); //配置hangfire
  214. app.UseResponseCaching().UseResponseCompression(); //启动Response缓存
  215. app.UseActivity();// 抽奖活动
  216. app.UseRouting(); // 放在 UseStaticFiles 之后
  217. app.UseEndpoints(endpoints =>
  218. {
  219. endpoints.MapControllers(); // 属性路由
  220. endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
  221. endpoints.MapHub<MyHub>("/hubs");
  222. });
  223. HangfireJobInit.Start(); //初始化定时任务
  224. Console.WriteLine("网站启动完成");
  225. }
  226. private static void InitSettings(DataContext db)
  227. {
  228. var dic = db.SystemSetting.ToDictionary(s => s.Name, s => s.Value); //初始化系统设置参数
  229. foreach (var (key, value) in dic)
  230. {
  231. CommonHelper.SystemSettings.TryAdd(key, value);
  232. }
  233. }
  234. private static void UseLuceneSearch(IHostEnvironment env, IHangfireBackJob hangfire, LuceneIndexerOptions luceneIndexerOptions)
  235. {
  236. Task.Run(() =>
  237. {
  238. Console.WriteLine("正在导入自定义词库...");
  239. double time = HiPerfTimer.Execute(() =>
  240. {
  241. var lines = File.ReadAllLines(Path.Combine(env.ContentRootPath, "App_Data", "CustomKeywords.txt"));
  242. var segmenter = new JiebaSegmenter();
  243. foreach (var word in lines)
  244. {
  245. segmenter.AddWord(word);
  246. }
  247. });
  248. Console.WriteLine($"导入自定义词库完成,耗时{time}s");
  249. });
  250. string lucenePath = Path.Combine(env.ContentRootPath, luceneIndexerOptions.Path);
  251. if (!Directory.Exists(lucenePath) || Directory.GetFiles(lucenePath).Length < 1)
  252. {
  253. Console.WriteLine("索引库不存在,开始自动创建Lucene索引库...");
  254. hangfire.CreateLuceneIndex();
  255. Console.WriteLine("索引库创建完成!");
  256. }
  257. }
  258. }
  259. /// <summary>
  260. /// hangfire授权拦截器
  261. /// </summary>
  262. public class MyRestrictiveAuthorizationFilter : IDashboardAuthorizationFilter
  263. {
  264. /// <summary>
  265. /// 授权校验
  266. /// </summary>
  267. /// <param name="context"></param>
  268. /// <returns></returns>
  269. public bool Authorize(DashboardContext context)
  270. {
  271. #if DEBUG
  272. return true;
  273. #endif
  274. var user = context.GetHttpContext().Session.Get<UserInfoDto>(SessionKey.UserInfo) ?? new UserInfoDto();
  275. return user.IsAdmin;
  276. }
  277. }
  278. }