123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228 |
- using IES.ExamServer.DI;
- using IES.ExamServer.DI.SignalRHost;
- using IES.ExamServer.Helper;
- using Microsoft.AspNetCore.Hosting.Server.Features;
- using Microsoft.AspNetCore.Hosting.Server;
- using Microsoft.AspNetCore.SpaServices;
- using Microsoft.AspNetCore.StaticFiles;
- using Microsoft.Extensions.Caching.Memory;
- using System.Text.Json;
- using System.Text.Json.Nodes;
- using VueCliMiddleware;
- using IES.ExamServer.Services;
- using System.Text;
- using IES.ExamServer.Filters;
- using IES.ExamServer.Helpers;
- using Microsoft.Extensions.Hosting;
- using System.Security.Principal;
- using Microsoft.Extensions.FileProviders;
- using System.Text.Encodings.Web;
- using System.Text.Unicode;
- using Microsoft.Extensions.Logging;
- using System.Runtime.InteropServices;
- using NLog.Extensions.Logging;
- namespace IES.ExamServer
- {
- public class Program: IDisposable
- {
- public async static Task Main(string[] args)
- {
- Console.OutputEncoding = Encoding.UTF8;
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)||RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
- { }
- else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
- {
- }
- //
- //var mutex = new Mutex(true, "IES.ExamServer", out var createdNew);
- //if (!createdNew)
- //{
- // // 防止多开,重复启动
- // Console.WriteLine("The application is already running.");
- // return;
- //}
- //ProcessHelper.CloseConhost();
- //AppDomain.CurrentDomain.ProcessExit += OnExit;
- var builder = WebApplication.CreateBuilder(args);
- string path = $"{builder.Environment.ContentRootPath}/Configs";
- //builder.WebHost.UseKestrel(options =>
- //{
- // options.ListenAnyIP(5001, listenOptions =>
- // {
- // listenOptions.UseHttps($"{path}/cert.pfx", "cdhabook") ;
- // });
- //});
- builder.Configuration.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
- builder.Services.AddSpaStaticFiles(opt => opt.RootPath = "ClientApp/dist");
- // Add services to the container.
- builder.Services.AddControllers().AddJsonOptions(options =>
- {
- // 设置 JSON 序列化选项
- options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); // 允许所有 Unicode 字符
- options.JsonSerializerOptions.WriteIndented = true; // 格式化输出(可选)
- }); ;
- builder.Services.AddHttpClient();
- builder.Services.AddSignalR();
- builder.Services.AddHttpContextAccessor();
- //此处能在Linux及MacOS运行,
- //Windows的路径是LocalApplicationData Path: C:\Users\john\AppData\Local
- //Linux的路径是LocalApplicationData Path: /home/john/.local/share,
- //MacOS 的路径LocalApplicationData Path: /Users/john/Library/Application Support
- string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- //string dbpath = $"{localAppDataPath}\\ExamServer\\LiteDB";
- string dbpath = Path.Combine(localAppDataPath, "ExamServer", "LiteDB");
- if (!System.IO.Directory.Exists(dbpath))
- {
- System.IO.Directory.CreateDirectory(dbpath);
- }
- string liteDBPath = $"Filename={dbpath}/data.db;Connection=shared";
- var connections_LiteDB = new List<LiteDBFactoryOptions>
- {
- new LiteDBFactoryOptions { Name = "Master", Connectionstring = liteDBPath}
- };
- builder.Services.AddLiteDB(connections_LiteDB);
- builder.Services.AddMemoryCache();
- // 注册 ConnectionService 为单例
- builder.Services.AddSingleton<CenterServiceConnectionService>();
- builder.Services.AddSingleton<ServiceInitializer>();
- builder.Services.AddCors(options =>
- {
- //options.AddDefaultPolicy(
- //builder =>
- //{
- // builder.AllowAnyOrigin()
- // .AllowAnyHeader()
- // .AllowAnyMethod();
- //});
- options.AddPolicy("any", builder =>
- {
- builder.SetIsOriginAllowed(x=>true)
- .AllowAnyMethod()
- .AllowAnyHeader()
- .AllowCredentials();
- });
- });
- builder.Services.AddMvcFilter<AuthTokenActionFilter>();
- // 添加自定义日志提供程序
- //builder.Logging.ClearProviders();
- //bool enableConsoleOutput = true;
- //builder.Logging.AddProvider(new CustomFileLoggerProvider(Path.Combine(Directory.GetCurrentDirectory(), "Logs"), enableConsoleOutput));
- // 添加日志服务
- builder.Logging.ClearProviders();
- builder.Logging.AddNLog();
- builder.Services.AddHostedService<SignalRCloudClientHub>();
- var app = builder.Build();
- // Configure the HTTP request pipeline.
- if (!app.Environment.IsDevelopment())
- {
- app.UseExceptionHandler("/Home/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();
- }
- else { app.UseDeveloperExceptionPage(); }
- app.UseHttpsRedirection();
- app.UseDefaultFiles();
- var contentTypeProvider = new FileExtensionContentTypeProvider();
- contentTypeProvider.Mappings[".txt"] = "text/plain";
- contentTypeProvider.Mappings[".jpg"] = "image/jpeg";
- contentTypeProvider.Mappings[".jpeg"] = "image/jpeg";
- contentTypeProvider.Mappings[".png"] = "image/png";
- contentTypeProvider.Mappings[".html"] = "text/html";
- contentTypeProvider.Mappings[".js"] = "application/javascript";
- contentTypeProvider.Mappings[".css"] = "text/css";
- contentTypeProvider.Mappings[".mp4"] = "video/mp4";
- contentTypeProvider.Mappings[".mp3"] = "audio/mpeg";
- contentTypeProvider.Mappings[".json"] = "application/json";
- contentTypeProvider.Mappings[".pdf"] = "application/pdf";
- string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package");
- if (!Directory.Exists(packagePath))
- {
- Directory.CreateDirectory(packagePath);
- }
- //new StaticFileOptions
- //{
- // FileProvider = new PhysicalFileProvider(
- // Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "package")),
- // RequestPath = "/package",
- // ContentTypeProvider = contentTypeProvider,
- //}
- app.UseStaticFiles();
- app.UseRouting();
- app.UseCors("any");
- app.UseAuthorization();
- app.MapHub<SignalRExamServerHub>("/signalr/exam").RequireCors("any");
- app.UseEndpoints(endpoints =>
- {
- // endpoints.MapHub<SignalRExamServerHub>("/signalr/exam").RequireCors("any");
- endpoints.MapControllers();
- // NOTE: VueCliProxy is meant for developement and hot module reload
- // NOTE: SSR has not been tested
- // Production systems should only need the UseSpaStaticFiles() (above)
- // You could wrap this proxy in either
- // if (System.Diagnostics.Debugger.IsAttached)
- // or a preprocessor such as #if DEBUG
- /*
- npm install -g @vue
- vue create app
- */
- #if DEBUG
- endpoints.MapToVueCliProxy(
- "{*path}",
- new SpaOptions { SourcePath = "ClientApp" },
- npmScript: (System.Diagnostics.Debugger.IsAttached) ? "serve" : null,
- // regex: "Compiled successfully",
- forceKill: true
- );
- #else
- endpoints.MapFallbackToFile("index.html");
- #endif
- });
- // 获取 ServiceInitializer 实例并初始化
- var connectionManager = app.Services.GetRequiredService<ServiceInitializer>();
- await connectionManager.InitializeAsync();
- await app.RunAsync();
- }
- //static void OnExit(object sender, EventArgs e)
- //{
- // Console.WriteLine("正在退出程序...");
- // // 执行任何需要的清理工作
- // // 例如: 保存状态,关闭文件和数据库连接等
- // // 通过调用 Environment.Exit 来结束进程
- // Environment.Exit(0);
- //}
- public void Dispose()
- {
- // 清理代码
- //Console.WriteLine("正在退出...");
- // 释放资源、关闭连接等
- }
- }
- public class SystemInfo
- {
- public string? id { get; set; }
- public string? version { get; set; }
- public string? description { get; set; }
- public long nowtime { get; set; }
- public string? region { get; set; }
- public string? ip { get; set; }
- public string? date { get; set; }
- public string? centerUrl { get; set; }
- }
- }
|