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

namespace EnterpriseCoreV3
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Threading.Tasks;
using CounsellorBL.Helper;
using CSRedis;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using SoldierData.EnterprizeV4;
using WebMvcEF;
public class Startup
{
const string CACHE_KEY_tb_sys_uploadlog = "CACHE_KEY_tb_sys_uploadlog";
const string CACHE_KEY_tb_sys_translation = "CACHE_KEY_tb_sys_translation";
const string CACHE_KEY_tb_sys_translation2 = "CACHE_KEY_tb_sys_translation2";
const string CACHE_KEY_tb_sys_system_setting = "CACHE_KEY_tb_sys_system_setting";
const string CACHE_KEY_tb_sys_system_setting2 = "CACHE_KEY_tb_sys_system_setting2";
// Translation
// System_setting
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
protected byte[] ObjectToByteArray(object obj)
{
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
//var csredis = new CSRedisClient("127.0.0.1:6379,password=25153819,poolsize=100");
//RedisHelper.Initialization(csredis);
//services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
//if (!csredis.Exists("classTest"))
//{
// csredis.Set("classTest", new tb_grp_article() { uid = "33" });
//}
//tb_grp_article a = csredis.Get< tb_grp_article>("classTest");
// csredis.Set("Test", $"AAAA - {DateTime.Now}");
//var redisDB = new CSRedisClient[16];
//for (var a = 0; a < redisDB.Length; a++)
// redisDB[a] = new CSRedisClient(Configuration.GetConnectionString("redis") + ",defualtDatabase=" + a);
//services.AddSingleton(redisDB);
services.AddSession(options =>
{
options.Cookie.HttpOnly = true;
});
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Default value is 30 MB
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = 51200000;// 50MB
});
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = 51200000;// 50MB
});
services.AddCors(options =>
{
// CorsPolicy ¬O¦Û­qªº Policy ¦WºÙ
options.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
services.AddMemoryCache();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0).AddNewtonsoftJson(o =>
{
o.UseCamelCasing(true);
o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
services.Configure<IISOptions>(options => { options.AutomaticAuthentication = true; }); // Windows Auth
services.AddAuthentication(IISDefaults.AuthenticationScheme); // Windows Auth
services.AddControllers().AddNewtonsoftJson();
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
IMemoryCache imc)
{
// Cache Init
if (!imc.TryGetValue(CACHE_KEY_tb_sys_uploadlog, out ConcurrentDictionary<string, tb_sys_uploadlog> dicMapUpload))
{
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
dicMapUpload = new ConcurrentDictionary<string, tb_sys_uploadlog>();
if(DownloadHelper.GetFilePaths(out List<tb_sys_uploadlog> ulRes) == null && ulRes.Any())
{
ulRes.ForEach(f=> {
dicMapUpload.TryAdd(f.uid, f);
});
}
imc.Set(CACHE_KEY_tb_sys_uploadlog, dicMapUpload, entryOptions);
}
if (!imc.TryGetValue(CACHE_KEY_tb_sys_translation, out ConcurrentDictionary<string, tb_sys_translation> dicMapTranslate))
{
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
dicMapTranslate = new ConcurrentDictionary<string, tb_sys_translation>();
if(TranslationHelper.GetTranslations(out List<tb_sys_translation> ulRes) == null && ulRes.Any())
{
ulRes.ForEach(f => {
dicMapTranslate.TryAdd(f.name, f);
});
}
imc.Set(CACHE_KEY_tb_sys_translation, dicMapTranslate, entryOptions);
imc.Set(CACHE_KEY_tb_sys_translation2, ulRes, entryOptions);
}
//
if (!imc.TryGetValue(CACHE_KEY_tb_sys_system_setting, out ConcurrentDictionary<string, tb_sys_system_setting> dicMapSetting))
{
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
dicMapSetting = new ConcurrentDictionary<string, tb_sys_system_setting>();
if (SystemSettingHelper.GetSettings(out List<tb_sys_system_setting> ulRes) == null && ulRes.Any())
{
ulRes.ForEach(f => {
dicMapSetting.TryAdd(f.name, f);
});
}
imc.Set(CACHE_KEY_tb_sys_system_setting, dicMapSetting, entryOptions);
imc.Set(CACHE_KEY_tb_sys_system_setting2, ulRes, entryOptions);
}
app.UseResponseCompression();
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseStatusCodePagesWithRedirects("/Error?code={0}");
}
app.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Frame-Options", "DENY");
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/Main/Index.html";
await next();
}
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "Views/Main")),
RequestPath = "/Main"
}).UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllers();
});
}
}
internal class LifetimeEventsHostedService : IHostedService
{
private readonly IHostApplicationLifetime _appLifetime;
private ProcessKiller officeKiller;
public LifetimeEventsHostedService(
IHostApplicationLifetime appLifetime)
{
_appLifetime = appLifetime;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStopping.Register(OnStopping);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private void OnStarted()
{
// ºÊ±±µ{§Ç
officeKiller = ProcessKiller.StartNew("soffice", 60);
}
private void OnStopping()
{
if (officeKiller != null)
{
officeKiller.Dispose();
}
}
}
}