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.

87 lines
2.5 KiB

  1. #if NETCORE
  2. using System;
  3. using System.Collections.Generic;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.AspNetCore.Builder;
  10. using System.Threading.Tasks;
  11. using System.Net;
  12. using System.Security.Cryptography.X509Certificates;
  13. using Microsoft.Extensions.Logging;
  14. using Microsoft.AspNetCore.Hosting.Server;
  15. namespace Apewer.Web
  16. {
  17. internal sealed class HttpSysStartup
  18. {
  19. public HttpSysStartup(IConfiguration configuration)
  20. {
  21. Configuration = configuration;
  22. }
  23. public IConfiguration Configuration { get; }
  24. // 此方法由运行时调用。
  25. // 可使用此方法添加服务到容器。
  26. public void ConfigureServices(IServiceCollection services)
  27. {
  28. // services.AddControllers();
  29. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  30. }
  31. // 此方法由运行时调用。
  32. // 可使用此方法配置 HTTP 请求命名管道。
  33. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<HttpSysStartup> logger, IServer server)
  34. {
  35. if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
  36. var wsOptions = new WebSocketOptions();
  37. wsOptions.KeepAliveInterval = TimeSpan.FromSeconds(20);
  38. app.UseWebSockets(wsOptions);
  39. app.Use(async (context, next) =>
  40. {
  41. var server = AspNetCore.Get(context.Connection.LocalPort);
  42. if (server == null) return;
  43. var wsa = server.WebSocket;
  44. if (wsa != null && context.WebSockets.IsWebSocketRequest)
  45. {
  46. try
  47. {
  48. using (var ws = context.WebSockets.AcceptWebSocketAsync())
  49. {
  50. wsa.Invoke(context, ws.Result);
  51. }
  52. }
  53. catch { }
  54. return;
  55. }
  56. var a = server.Context;
  57. if (a != null)
  58. {
  59. try
  60. {
  61. a.Invoke(context);
  62. }
  63. catch { }
  64. return;
  65. }
  66. await next.Invoke();
  67. });
  68. }
  69. }
  70. }
  71. #endif