title: How to use web sockets in C# .NET Core 3.1?
body: <p>I am trying to implement live notifications in my web application. Only the users which are administrators in my web app should see the notifications.<br />
  So I setup the web socket in my startup.cs file <code>which I think is not the right way</code></p>
  <p>Startup.cs</p>
  <pre><code>var webSocketOptions = new WebSocketOptions()
  {
      KeepAliveInterval = TimeSpan.FromSeconds(120),
      ReceiveBufferSize = 4 * 1024
  };
  app.UseWebSockets(webSocketOptions);
  app.Use(async (context, next) =&gt;
      {
           if (context.Request.Path == &quot;/ws&quot;)
           {
               if (context.WebSockets.IsWebSocketRequest)
               {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                          
               }
               else
               {
                   context.Response.StatusCode = 400;
               }
           }
           else
           {
              await next();
           }
     });
  </code></pre>
  <p>and this is my Javascript</p>
  <pre><code>window.onload = () =&gt; {
      if (/*User is Admin*/) {
  
          //Establish Websocket
          var socket = new WebSocket(&quot;wss:localhost:44301/ws&quot;);
  
          console.log(socket.readyState);
  
          socket.onerror = function (error) {
              console.log('WebSocket Error: ' + error);
          };
  
          socket.onopen = function (event) {          
              console.log(&quot;Socket connection opened&quot;)
          };
  
          // Handle messages sent by the server.
          socket.onmessage = function (event) {
              var data = event.data;
              console.log(data);
              //Draw some beautiful HTML notification
          };
      }
  }
  </code></pre>
  <p>now this all works, but I don't know how to send messages from my server controllers, something like this</p>
  <pre><code>[HttpGet]
  public async Task&lt;IActionResult&gt; Foo(WebSocket webSocket)
  {
      //What I am trying to do is send message from the open web socket connection.
      var buffer = new byte[1024 * 4];
      buffer = Encoding.UTF8.GetBytes(&quot;Foo&quot;);
  
      await webSocket.SendAsync(new ArraySegment&lt;byte&gt;(buffer),WebSocketMessageType.Text,true,CancellationToken.None);
      return View()
  }
  </code></pre>
  <p>I don't know how to approach this. What I wanna do is if the user is admin, open web socket and send some data from the other users actions, (which means writing messages from that opened web socket from some of my controllers)</p>