using IES.ExamServer.DI; using IES.ExamServer.DI.SignalRHost; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System.Configuration; using System.IO; using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; using System.Windows; using System.Windows.Interop; namespace IES.ExamServer { public partial class App : Application, IAsyncDisposable { public WebApplication? WebApplication { get; private set; } public async ValueTask DisposeAsync() { if (WebApplication is not null) { await WebApplication.DisposeAsync(); } GC.SuppressFinalize(this); } private async void ApplicationStartup(object sender, StartupEventArgs e) { // 这里是创建 ASP.NET 版通用主机的代码 var builder = WebApplication.CreateBuilder(Environment.GetCommandLineArgs()); builder.Configuration.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); //builder.WebHost.UseUrls("http://*:5000;https://*:5001"); // 注册主窗口和其他服务 builder.Services.AddControllersWithViews(); builder.Services.AddSingleton(); builder.Services.AddSingleton(this); builder.Services.AddHttpClient(); builder.Services.AddSignalR(); builder.Services.AddHttpContextAccessor(); string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string dbpath = $"{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 { new LiteDBFactoryOptions { Name = "Master", Connectionstring = liteDBPath} }; builder.Services.AddLiteDB(connections_LiteDB); builder.Services.AddMemoryCache(); string path = $"{builder.Environment.ContentRootPath}/Configs"; builder.Services.AddCors(options => { options.AddDefaultPolicy( builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); var app = builder.Build(); // 这里是文件类型映射,如果你的静态文件在浏览器中加载报 404,那么需要在这里注册,这里我加载一个 3D 场景文件的类型 var contentTypeProvider = new FileExtensionContentTypeProvider(); contentTypeProvider.Mappings[".glb"] = "model/gltf-binary"; app.UseDefaultFiles(); app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = contentTypeProvider, }); // 你如果使用了 Vue Router 或者其他前端路由了,需要在这里添加这句话让路由返回前端,而不是 ASP.NET Core 处理 app.MapFallbackToFile("/index.html"); //PRODUCTION uses webpack static files app.UseRouting(); app.UseHttpsRedirection(); //開發中暫時關掉 //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的 //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前 app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.MapHub("/signalr/screen").RequireCors("any"); WebApplication = app; // 处理退出事件,退出 App 时关闭 ASP.NET Core Exit += async (s, e) => await WebApplication.StopAsync(); // 显示主窗口 MainWindow = app.Services.GetRequiredService(); MainWindow.Show(); IMemoryCache? cache = app.Services.GetRequiredService(); IHttpClientFactory? clientFactory = app.Services.GetRequiredService(); LiteDBFactory liteDBFactory = app.Services.GetRequiredService(); JsonNode? data = null; try { string? CenterUrl = builder.Configuration.GetValue("ExamServer:CenterUrl"); var httpclient = clientFactory.CreateClient(); httpclient.Timeout= TimeSpan.FromSeconds(10); HttpResponseMessage message = await httpclient.PostAsJsonAsync($"{CenterUrl}/core/system-info", new { }); if (message.IsSuccessStatusCode) { string content = await message.Content.ReadAsStringAsync(); data = JsonSerializer.Deserialize(content); data!["centerUrl"]=CenterUrl; cache.Set("Server:Center:Data", data); SystemInfo? system= JsonSerializer.Deserialize(data); system!.id= $"{DateTimeOffset.Now.ToUnixTimeMilliseconds()}"; liteDBFactory.GetLiteDatabase().GetCollection("System").Insert(system); } } catch (Exception ex) { } await app.RunAsync().ConfigureAwait(false); } } 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; } } }