title: ASP.NET Core WebSockets
body: <p>I'm trying to have a WebSocket server up and running on ASP.NET Core. I created an empty web project <code>dotnet new web</code> changed the <code>Program.cs</code> to:</p>
  <pre class="lang-cs prettyprint-override"><code>public static void Main(string[] args) {
      Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =&gt; {
          webBuilder.UseStartup&lt;Startup&gt;();
      })
      .Build()
      .Run();
  }
  </code></pre>
  <p>And <code>Startup.cs</code>'s <code>ConfigureServices</code> method to:</p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services) {
      services.AddControllers();
      services.AddWebSockets();
  }
  </code></pre>
  <p>And <code>Configure</code> method to:</p>
  <pre class="lang-cs prettyprint-override"><code>public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
      app.UseWebSockets();
      app.UseRouting();
      app.UseEndpoints(endpoints =&gt; {
          endpoints.MapControllers();
          endpoints.MapConnectionHandler&lt;WebSocketHandler&gt;(&quot;/ws&quot;);
      });
  }
  </code></pre>
  <p>And my <code>WebSocketHandler</code>'s <code>OnConnectedAsync</code> method I've the following:</p>
  <pre class="lang-cs prettyprint-override"><code>public override async Task OnConnectedAsync(ConnectionContext connection) 
  {
      var context = connection.GetHttpContext();
      var endpoint = $&quot;{connection.RemoteEndPoint}&quot;;
  
      if (!context.WebSockets.IsWebSocketRequest) {
          connection.Abort();
          _logger.LogCritical($&quot;Request from {endpoint} endpoint aborted.&quot;);
          return;
      }
  
      var websocket = await context.WebSockets.AcceptWebSocketAsync();
      _logger.LogInformation($&quot;WebSocket request from {endpoint} endpoint accepted!&quot;);
  }
  </code></pre>
  <p>The problem arises when I try to connect to <code>APP_URL/ws</code> and each time the server closes the connection as soon as it receives the request. Here are the logs: <a href="https://pastebin.com/raw/34yu7thw" rel="noreferrer">https://pastebin.com/raw/34yu7thw</a></p>
  <p>If I place a <code>Task.Delay(-1)</code> at the end of <code>OnConnectedAsync</code> method, it keeps the connection open but drops incoming connections.</p>
  <p>I have searched MSDocs and haven't been able to find much documentation on how to use <code>MapConnectionHandler&lt;T&gt;</code>.</p>
  <p>Would it be safe for me to have a while loop which receives messages from multiple clients in <code>OnConnectedAsync</code>?
  Is this not the right way to handle websocket connections?
  Is <code>MapConnectionHandler&lt;T&gt;</code> transient?</p>
  <p>I'm really confused and can't figure out it's behavior.</p>