App.xaml.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.StaticFiles;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using System.Windows;
  6. namespace IES.ExamServer
  7. {
  8. public partial class App : Application, IAsyncDisposable
  9. {
  10. public WebApplication? WebApplication { get; private set; }
  11. public async ValueTask DisposeAsync()
  12. {
  13. if (WebApplication is not null)
  14. {
  15. await WebApplication.DisposeAsync();
  16. }
  17. GC.SuppressFinalize(this);
  18. }
  19. private async void ApplicationStartup(object sender, StartupEventArgs e)
  20. {
  21. // 这里是创建 ASP.NET 版通用主机的代码
  22. var builder = WebApplication.CreateBuilder(Environment.GetCommandLineArgs());
  23. builder.WebHost.UseUrls("http://*:5000;https://*:5001");
  24. // 注册主窗口和其他服务
  25. builder.Services.AddControllersWithViews();
  26. builder.Services.AddSingleton<MainWindow>();
  27. builder.Services.AddSingleton(this);
  28. var app = builder.Build();
  29. // 这里是文件类型映射,如果你的静态文件在浏览器中加载报 404,那么需要在这里注册,这里我加载一个 3D 场景文件的类型
  30. var contentTypeProvider = new FileExtensionContentTypeProvider();
  31. contentTypeProvider.Mappings[".glb"] = "model/gltf-binary";
  32. app.UseStaticFiles(new StaticFileOptions
  33. {
  34. ContentTypeProvider = contentTypeProvider,
  35. });
  36. // 你如果使用了 Vue Router 或者其他前端路由了,需要在这里添加这句话让路由返回前端,而不是 ASP.NET Core 处理
  37. app.MapFallbackToFile("/index.html");
  38. //PRODUCTION uses webpack static files
  39. app.UseRouting();
  40. app.UseHttpsRedirection(); //開發中暫時關掉
  41. //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的
  42. //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前
  43. app.UseAuthentication();
  44. app.UseAuthorization();
  45. app.MapControllers();
  46. WebApplication = app;
  47. // 处理退出事件,退出 App 时关闭 ASP.NET Core
  48. Exit += async (s, e) => await WebApplication.StopAsync();
  49. // 显示主窗口
  50. MainWindow = app.Services.GetRequiredService<MainWindow>();
  51. MainWindow.Show();
  52. await app.RunAsync().ConfigureAwait(false);
  53. }
  54. }
  55. }