You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

288 lines
11 KiB

  1. namespace EnterpriseCoreV3
  2. {
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.IO.Compression;
  8. using System.Linq;
  9. using System.Runtime.Serialization.Formatters.Binary;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using CounsellorBL.Helper;
  13. using CSRedis;
  14. using Microsoft.AspNetCore.Builder;
  15. using Microsoft.AspNetCore.Hosting;
  16. using Microsoft.AspNetCore.Http;
  17. using Microsoft.AspNetCore.Mvc;
  18. using Microsoft.AspNetCore.ResponseCompression;
  19. using Microsoft.AspNetCore.Server.IISIntegration;
  20. using Microsoft.AspNetCore.Server.Kestrel.Core;
  21. using Microsoft.Extensions.Caching.Distributed;
  22. using Microsoft.Extensions.Caching.Memory;
  23. using Microsoft.Extensions.Configuration;
  24. using Microsoft.Extensions.DependencyInjection;
  25. using Microsoft.Extensions.FileProviders;
  26. using Microsoft.Extensions.Hosting;
  27. using SoldierData.EnterprizeV4;
  28. using WebMvcEF;
  29. public class Startup
  30. {
  31. const string CACHE_KEY_tb_sys_uploadlog = "CACHE_KEY_tb_sys_uploadlog";
  32. const string CACHE_KEY_tb_sys_translation = "CACHE_KEY_tb_sys_translation";
  33. const string CACHE_KEY_tb_sys_translation2 = "CACHE_KEY_tb_sys_translation2";
  34. const string CACHE_KEY_tb_sys_system_setting = "CACHE_KEY_tb_sys_system_setting";
  35. const string CACHE_KEY_tb_sys_system_setting2 = "CACHE_KEY_tb_sys_system_setting2";
  36. // Translation
  37. // System_setting
  38. public Startup(IConfiguration configuration)
  39. {
  40. Configuration = configuration;
  41. }
  42. public IConfiguration Configuration { get; }
  43. protected byte[] ObjectToByteArray(object obj)
  44. {
  45. var binaryFormatter = new BinaryFormatter();
  46. using (var memoryStream = new MemoryStream())
  47. {
  48. binaryFormatter.Serialize(memoryStream, obj);
  49. return memoryStream.ToArray();
  50. }
  51. }
  52. // This method gets called by the runtime. Use this method to add services to the container.
  53. public void ConfigureServices(IServiceCollection services)
  54. {
  55. services.AddDistributedMemoryCache();
  56. //var csredis = new CSRedisClient("127.0.0.1:6379,password=25153819,poolsize=100");
  57. //RedisHelper.Initialization(csredis);
  58. //services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
  59. //if (!csredis.Exists("classTest"))
  60. //{
  61. // csredis.Set("classTest", new tb_grp_article() { uid = "33" });
  62. //}
  63. //tb_grp_article a = csredis.Get< tb_grp_article>("classTest");
  64. // csredis.Set("Test", $"AAAA - {DateTime.Now}");
  65. //var redisDB = new CSRedisClient[16];
  66. //for (var a = 0; a < redisDB.Length; a++)
  67. // redisDB[a] = new CSRedisClient(Configuration.GetConnectionString("redis") + ",defualtDatabase=" + a);
  68. //services.AddSingleton(redisDB);
  69. services.AddSession(options =>
  70. {
  71. options.Cookie.HttpOnly = true;
  72. });
  73. services.Configure<BrotliCompressionProviderOptions>(options =>
  74. {
  75. options.Level = CompressionLevel.Fastest;
  76. });
  77. services.Configure<CookiePolicyOptions>(options =>
  78. {
  79. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  80. options.CheckConsentNeeded = context => true;
  81. options.MinimumSameSitePolicy = SameSiteMode.None;
  82. });
  83. // Default value is 30 MB
  84. services.Configure<IISServerOptions>(options =>
  85. {
  86. options.MaxRequestBodySize = 51200000;// 50MB
  87. });
  88. services.Configure<KestrelServerOptions>(options =>
  89. {
  90. options.Limits.MaxRequestBodySize = 51200000;// 50MB
  91. });
  92. services.AddCors(options =>
  93. {
  94. // CorsPolicy �O�ۭq�� Policy �W��
  95. options.AddPolicy("CorsPolicy", policy =>
  96. {
  97. policy.AllowAnyOrigin()
  98. .AllowAnyHeader()
  99. .AllowAnyMethod();
  100. });
  101. });
  102. services.AddResponseCompression(options =>
  103. {
  104. options.Providers.Add<BrotliCompressionProvider>();
  105. options.Providers.Add<GzipCompressionProvider>();
  106. options.MimeTypes =
  107. ResponseCompressionDefaults.MimeTypes.Concat(
  108. new[] { "image/svg+xml" });
  109. });
  110. services.AddMemoryCache();
  111. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  112. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddNewtonsoftJson(o =>
  113. {
  114. o.UseCamelCasing(true);
  115. o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
  116. });
  117. services.Configure<IISOptions>(options => { options.AutomaticAuthentication = true; }); // Windows Auth
  118. services.AddAuthentication(IISDefaults.AuthenticationScheme); // Windows Auth
  119. services.AddControllers().AddNewtonsoftJson();
  120. services.AddControllersWithViews().AddNewtonsoftJson();
  121. services.AddRazorPages().AddNewtonsoftJson();
  122. }
  123. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  124. public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
  125. IMemoryCache imc)
  126. {
  127. // Cache Init
  128. if (!imc.TryGetValue(CACHE_KEY_tb_sys_uploadlog, out ConcurrentDictionary<string, tb_sys_uploadlog> dicMapUpload))
  129. {
  130. var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
  131. dicMapUpload = new ConcurrentDictionary<string, tb_sys_uploadlog>();
  132. if(DownloadHelper.GetFilePaths(out List<tb_sys_uploadlog> ulRes) == null && ulRes.Any())
  133. {
  134. ulRes.ForEach(f=> {
  135. dicMapUpload.TryAdd(f.uid, f);
  136. });
  137. }
  138. imc.Set(CACHE_KEY_tb_sys_uploadlog, dicMapUpload, entryOptions);
  139. }
  140. if (!imc.TryGetValue(CACHE_KEY_tb_sys_translation, out ConcurrentDictionary<string, tb_sys_translation> dicMapTranslate))
  141. {
  142. var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
  143. dicMapTranslate = new ConcurrentDictionary<string, tb_sys_translation>();
  144. if(TranslationHelper.GetTranslations(out List<tb_sys_translation> ulRes) == null && ulRes.Any())
  145. {
  146. ulRes.ForEach(f => {
  147. dicMapTranslate.TryAdd(f.name, f);
  148. });
  149. }
  150. imc.Set(CACHE_KEY_tb_sys_translation, dicMapTranslate, entryOptions);
  151. imc.Set(CACHE_KEY_tb_sys_translation2, ulRes, entryOptions);
  152. }
  153. //
  154. if (!imc.TryGetValue(CACHE_KEY_tb_sys_system_setting, out ConcurrentDictionary<string, tb_sys_system_setting> dicMapSetting))
  155. {
  156. var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
  157. dicMapSetting = new ConcurrentDictionary<string, tb_sys_system_setting>();
  158. if (SystemSettingHelper.GetSettings(out List<tb_sys_system_setting> ulRes) == null && ulRes.Any())
  159. {
  160. ulRes.ForEach(f => {
  161. dicMapSetting.TryAdd(f.name, f);
  162. });
  163. }
  164. imc.Set(CACHE_KEY_tb_sys_system_setting, dicMapSetting, entryOptions);
  165. imc.Set(CACHE_KEY_tb_sys_system_setting2, ulRes, entryOptions);
  166. }
  167. app.UseResponseCompression();
  168. app.UseCors("CorsPolicy");
  169. if (env.IsDevelopment())
  170. {
  171. app.UseDeveloperExceptionPage();
  172. }
  173. else
  174. {
  175. app.UseExceptionHandler("/Error");
  176. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  177. app.UseHsts();
  178. app.UseStatusCodePagesWithRedirects("/Error?code={0}");
  179. }
  180. app.UseHttpsRedirection();
  181. app.UseCookiePolicy();
  182. app.UseRouting();
  183. app.UseCors("CorsPolicy");
  184. app.UseAuthorization();
  185. app.Use(async (context, next) =>
  186. {
  187. context.Response.Headers.Add("X-Frame-Options", "DENY");
  188. await next();
  189. if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
  190. {
  191. context.Request.Path = "/Main/Index.html";
  192. await next();
  193. }
  194. });
  195. app.UseStaticFiles(new StaticFileOptions
  196. {
  197. FileProvider = new PhysicalFileProvider(
  198. Path.Combine(Directory.GetCurrentDirectory(), "Views/Main")),
  199. RequestPath = "/Main"
  200. }).UseEndpoints(endpoints =>
  201. {
  202. endpoints.MapControllerRoute(
  203. name: "default",
  204. pattern: "{controller=Home}/{action=Index}/{id?}");
  205. endpoints.MapControllers();
  206. });
  207. }
  208. }
  209. internal class LifetimeEventsHostedService : IHostedService
  210. {
  211. private readonly IHostApplicationLifetime _appLifetime;
  212. private ProcessKiller officeKiller;
  213. public LifetimeEventsHostedService(
  214. IHostApplicationLifetime appLifetime)
  215. {
  216. _appLifetime = appLifetime;
  217. }
  218. public Task StartAsync(CancellationToken cancellationToken)
  219. {
  220. _appLifetime.ApplicationStarted.Register(OnStarted);
  221. _appLifetime.ApplicationStopping.Register(OnStopping);
  222. return Task.CompletedTask;
  223. }
  224. public Task StopAsync(CancellationToken cancellationToken)
  225. {
  226. return Task.CompletedTask;
  227. }
  228. private void OnStarted()
  229. {
  230. // �ʱ��{��
  231. officeKiller = ProcessKiller.StartNew("soffice", 60);
  232. }
  233. private void OnStopping()
  234. {
  235. if (officeKiller != null)
  236. {
  237. officeKiller.Dispose();
  238. }
  239. }
  240. }
  241. }