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.

98 lines
3.0 KiB

4 years ago
  1. #if NETCORE
  2. using System;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.Extensions.Hosting;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.AspNetCore.Builder;
  9. using System.Threading.Tasks;
  10. namespace Apewer.Web
  11. {
  12. /// <summary></summary>
  13. public abstract class AspNetCoreStartup
  14. {
  15. /// <summary>处理 WebSocket 请求。</summary>
  16. /// <remarks>默认值:FALSE。</remarks>
  17. public virtual bool UseWebSocket { get; protected set; } = false;
  18. /// <summary>WebSocket 保持活动的间隔时间,单位为秒。</summary>
  19. /// <remarks>默认值:10。</remarks>
  20. public virtual int KeepAlive { get; protected set; } = 10;
  21. /// <summary>处理请求。</summary>
  22. /// <param name="context"></param>
  23. public abstract void OnContext(HttpContext context);
  24. /// <summary>处理 WebSocket 请求。</summary>
  25. public virtual void OnWebSocket(HttpContext context, System.Net.WebSockets.WebSocket webSocket) { }
  26. #region Runtime
  27. bool _usedWebSocket = false;
  28. IConfiguration _configuration;
  29. /// <summary></summary>
  30. public AspNetCoreStartup() { }
  31. /// <summary></summary>
  32. public AspNetCoreStartup(IConfiguration configuration) => _configuration = configuration;
  33. /// <summary>使用此方法添加服务到容器。</summary>
  34. /// <remarks>此方法由运行时调用。</remarks>
  35. public void ConfigureServices(IServiceCollection services)
  36. {
  37. services.AddControllers();
  38. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  39. }
  40. /// <remarks>此方法由运行时调用。</remarks>
  41. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  42. {
  43. if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
  44. _usedWebSocket = UseWebSocket;
  45. if (_usedWebSocket)
  46. {
  47. var wsOptions = new WebSocketOptions();
  48. var keepAlive = KeepAlive;
  49. if (keepAlive > 0) wsOptions.KeepAliveInterval = TimeSpan.FromSeconds(keepAlive);
  50. app.UseWebSockets(wsOptions);
  51. }
  52. app.Run(Handler);
  53. }
  54. Task Handler(HttpContext context)
  55. {
  56. try
  57. {
  58. if (_usedWebSocket && UseWebSocket)
  59. {
  60. if (context.WebSockets.IsWebSocketRequest)
  61. {
  62. using (var ws = context.WebSockets.AcceptWebSocketAsync())
  63. {
  64. OnWebSocket(context, ws.Result);
  65. }
  66. return Task.CompletedTask;
  67. }
  68. }
  69. OnContext(context);
  70. }
  71. catch { }
  72. return Task.CompletedTask;
  73. }
  74. #endregion
  75. }
  76. }
  77. #endif