App.xaml.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. using IES.ExamServer.DI;
  2. using IES.ExamServer.DI.SignalRHost;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.AspNetCore.StaticFiles;
  6. using Microsoft.Extensions.Caching.Memory;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.DependencyInjection.Extensions;
  10. using System.Configuration;
  11. using System.IO;
  12. using System.Net.Http;
  13. using System.Net.Http.Json;
  14. using System.Text.Json;
  15. using System.Text.Json.Nodes;
  16. using System.Windows;
  17. using System.Windows.Interop;
  18. namespace IES.ExamServer
  19. {
  20. public partial class App : Application, IAsyncDisposable
  21. {
  22. public WebApplication? WebApplication { get; private set; }
  23. public async ValueTask DisposeAsync()
  24. {
  25. if (WebApplication is not null)
  26. {
  27. await WebApplication.DisposeAsync();
  28. }
  29. GC.SuppressFinalize(this);
  30. }
  31. private async void ApplicationStartup(object sender, StartupEventArgs e)
  32. {
  33. // 这里是创建 ASP.NET 版通用主机的代码
  34. var builder = WebApplication.CreateBuilder(Environment.GetCommandLineArgs());
  35. builder.Configuration.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  36. //builder.WebHost.UseUrls("http://*:5000;https://*:5001");
  37. // 注册主窗口和其他服务
  38. builder.Services.AddControllersWithViews();
  39. builder.Services.AddSingleton<MainWindow>();
  40. builder.Services.AddSingleton(this);
  41. builder.Services.AddHttpClient();
  42. builder.Services.AddSignalR();
  43. builder.Services.AddHttpContextAccessor();
  44. string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
  45. string dbpath = $"{localAppDataPath}\\ExamServer\\LiteDB";
  46. if (!System.IO.Directory.Exists(dbpath))
  47. {
  48. System.IO.Directory.CreateDirectory(dbpath);
  49. }
  50. string liteDBPath = $"Filename={dbpath}\\data.db;Connection=shared";
  51. var connections_LiteDB = new List<LiteDBFactoryOptions>
  52. {
  53. new LiteDBFactoryOptions { Name = "Master", Connectionstring = liteDBPath}
  54. };
  55. builder.Services.AddLiteDB(connections_LiteDB);
  56. builder.Services.AddMemoryCache();
  57. string path = $"{builder.Environment.ContentRootPath}/Configs";
  58. builder.Services.AddCors(options =>
  59. {
  60. options.AddDefaultPolicy(
  61. builder =>
  62. {
  63. builder.AllowAnyOrigin()
  64. .AllowAnyHeader()
  65. .AllowAnyMethod();
  66. });
  67. });
  68. var app = builder.Build();
  69. // 这里是文件类型映射,如果你的静态文件在浏览器中加载报 404,那么需要在这里注册,这里我加载一个 3D 场景文件的类型
  70. var contentTypeProvider = new FileExtensionContentTypeProvider();
  71. contentTypeProvider.Mappings[".glb"] = "model/gltf-binary";
  72. app.UseDefaultFiles();
  73. app.UseStaticFiles(new StaticFileOptions
  74. {
  75. ContentTypeProvider = contentTypeProvider,
  76. });
  77. // 你如果使用了 Vue Router 或者其他前端路由了,需要在这里添加这句话让路由返回前端,而不是 ASP.NET Core 处理
  78. app.MapFallbackToFile("/index.html");
  79. //PRODUCTION uses webpack static files
  80. app.UseRouting();
  81. app.UseHttpsRedirection(); //開發中暫時關掉
  82. //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的
  83. //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前
  84. app.UseAuthentication();
  85. app.UseAuthorization();
  86. app.MapControllers();
  87. app.MapHub<SignalRExamServerHub>("/signalr/screen").RequireCors("any");
  88. WebApplication = app;
  89. // 处理退出事件,退出 App 时关闭 ASP.NET Core
  90. Exit += async (s, e) => await WebApplication.StopAsync();
  91. // 显示主窗口
  92. MainWindow = app.Services.GetRequiredService<MainWindow>();
  93. MainWindow.Show();
  94. IMemoryCache? cache = app.Services.GetRequiredService<IMemoryCache>();
  95. IHttpClientFactory? clientFactory = app.Services.GetRequiredService<IHttpClientFactory>();
  96. LiteDBFactory liteDBFactory = app.Services.GetRequiredService<LiteDBFactory>();
  97. JsonNode? data = null;
  98. try
  99. {
  100. string? CenterUrl = builder.Configuration.GetValue<string>("ExamServer:CenterUrl");
  101. var httpclient = clientFactory.CreateClient();
  102. httpclient.Timeout= TimeSpan.FromSeconds(10);
  103. HttpResponseMessage message = await httpclient.PostAsJsonAsync($"{CenterUrl}/core/system-info", new { });
  104. if (message.IsSuccessStatusCode)
  105. {
  106. string content = await message.Content.ReadAsStringAsync();
  107. data = JsonSerializer.Deserialize<JsonNode>(content);
  108. data!["centerUrl"]=CenterUrl;
  109. cache.Set("Server:Center:Data", data);
  110. SystemInfo? system= JsonSerializer.Deserialize<SystemInfo>(data);
  111. system!.id= $"{DateTimeOffset.Now.ToUnixTimeMilliseconds()}";
  112. liteDBFactory.GetLiteDatabase().GetCollection<SystemInfo>("System").Insert(system);
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. }
  118. await app.RunAsync().ConfigureAwait(false);
  119. }
  120. }
  121. public class SystemInfo
  122. {
  123. public string? id { get; set; }
  124. public string? version { get; set; }
  125. public string? description { get; set; }
  126. public long nowtime { get; set; }
  127. public string? region { get; set; }
  128. public string? ip { get; set; }
  129. public string? date { get; set; }
  130. public string? centerUrl { get; set; }
  131. }
  132. }