aspnetcore/fundamentals/websockets/includes/websockets3-5.md
:::moniker range="< aspnetcore-6.0 >= aspnetcore-3.1"
This article explains how to get started with WebSockets in ASP.NET Core. WebSocket (RFC 6455) is a protocol that enables two-way persistent communication channels over TCP connections. It's used in apps that benefit from fast, real-time communication, such as chat, dashboard, and game apps.
View or download sample code (how to download). How to run.
ASP.NET Core SignalR is a library that simplifies adding real-time web functionality to apps. It uses WebSockets whenever possible.
For most applications, we recommend SignalR over raw WebSockets. SignalR provides transport fallback for environments where WebSockets isn't available. It also provides a basic remote procedure call app model. And in most scenarios, SignalR has no significant performance disadvantage compared to using raw WebSockets.
For some apps, gRPC on .NET provides an alternative to WebSockets.
Add the WebSockets middleware in the Configure method of the Startup class:
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs" id="snippet_UseWebSockets":::
[!NOTE] If you would like to accept WebSocket requests in a controller, the call to
app.UseWebSocketsmust occur beforeapp.UseEndpoints.
The following settings can be configured:
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs" id="snippet_UseWebSocketsOptions":::
Somewhere later in the request life cycle (later in the Configure method or in an action method, for example) check if it's a WebSocket request and accept the WebSocket request.
The following example is from later in the Configure method:
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs" id="snippet_AcceptWebSocket" highlight="7":::
A WebSocket request could come in on any URL, but this sample code only accepts requests for /ws.
A similar approach can be taken in a controller method:
:::code language="csharp" source="~/fundamentals/websockets/samples/6.x/WebSocketsSample/Controllers/WebSocketController.cs" id="snippet":::
When using a WebSocket, you must keep the middleware pipeline running for the duration of the connection. If you attempt to send or receive a WebSocket message after the middleware pipeline ends, you may get an exception like the following:
System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake. ---> System.ObjectDisposedException: Cannot write to the response body, the response has completed.
Object name: 'HttpResponseStream'.
If you're using a background service to write data to a WebSocket, make sure you keep the middleware pipeline running. Do this by using a xref:System.Threading.Tasks.TaskCompletionSource%601. Pass the TaskCompletionSource to your background service and have it call xref:System.Threading.Tasks.TaskCompletionSource%601.TrySetResult%2A when you finish with the WebSocket. Then await the xref:System.Threading.Tasks.TaskCompletionSource%601.Task property during the request, as shown in the following example:
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup2.cs" id="snippet_AcceptWebSocket":::
The WebSocket closed exception can also happen when returning too soon from an action method. When accepting a socket in an action method, wait for the code that uses the socket to complete before returning from the action method.
Never use Task.Wait, Task.Result, or similar blocking calls to wait for the socket to complete, as that can cause serious threading issues. Always use await.
The AcceptWebSocketAsync method upgrades the TCP connection to a WebSocket connection and provides a xref:System.Net.WebSockets.WebSocket object. Use the WebSocket object to send and receive messages.
The code shown earlier that accepts the WebSocket request passes the WebSocket object to an Echo method. The code receives a message and immediately sends back the same message. Messages are sent and received in a loop until the client closes the connection:
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs" id="snippet_Echo":::
When accepting the WebSocket connection before beginning the loop, the middleware pipeline ends. Upon closing the socket, the pipeline unwinds. That is, the request stops moving forward in the pipeline when the WebSocket is accepted. When the loop is finished and the socket is closed, the request proceeds back up the pipeline.
The server isn't automatically informed when the client disconnects due to loss of connectivity. The server receives a disconnect message only if the client sends it, which can't be done if the internet connection is lost. If you want to take some action when that happens, set a timeout after nothing is received from the client within a certain time window.
If the client isn't always sending messages and you don't want to time out just because the connection goes idle, have the client use a timer to send a ping message every X seconds. On the server, if a message hasn't arrived within 2*X seconds after the previous one, terminate the connection and report that the client disconnected. Wait for twice the expected time interval to leave extra time for network delays that might hold up the ping message.
[!NOTE] The internal
ManagedWebSockethandles the Ping/Pong frames implicitly to keep the connection alive if theKeepAliveIntervaloption is greater than zero, which defaults to 30 seconds (TimeSpan.FromSeconds(30)).
The protections provided by CORS don't apply to WebSockets. Browsers do not:
Access-Control headers when making WebSocket requests.However, browsers do send the Origin header when issuing WebSocket requests. Applications should be configured to validate these headers to ensure that only WebSockets coming from the expected origins are allowed.
If you're hosting your server on "https://server.com" and hosting your client on "https://client.com", add "https://client.com" to the xref:Microsoft.AspNetCore.Builder.WebSocketOptions.AllowedOrigins%2A list for WebSockets to verify.
:::code language="csharp" source="~/fundamentals/websockets/samples/2.x/WebSocketsSample/Startup.cs" id="snippet_UseWebSocketsOptionsAO" highlight="6-7":::
[!NOTE] The
Originheader is controlled by the client and, like theRefererheader, can be faked. Do not use these headers as an authentication mechanism.
Windows Server 2012 or later and Windows 8 or later with IIS/IIS Express 8 or later has support for the WebSocket protocol.
[!NOTE] WebSockets are always enabled when using IIS Express.
To enable support for the WebSocket protocol on Windows Server 2012 or later:
[!NOTE] These steps are not required when using IIS Express
To enable support for the WebSocket protocol on Windows 8 or later:
[!NOTE] These steps are not required when using IIS Express
If using the WebSocket support in socket.io on Node.js, disable the default IIS WebSocket module using the webSocket element in web.config or applicationHost.config. If this step isn't performed, the IIS WebSocket module attempts to handle the WebSocket communication rather than Node.js and the app.
<webSocket enabled="false" />
The sample app that accompanies this article is an echo app. It has a webpage that makes WebSocket connections, and the server resends any messages it receives back to the client. The sample app isn't configured to run from Visual Studio with IIS Express, so run the app in a command shell with dotnet run and navigate in a browser to http://localhost:5000. The webpage shows the connection status:
:::image source="~/fundamentals/websockets/_static/start.png" alt-text="Initial state of webpage before WebSockets connection":::
Select Connect to send a WebSocket request to the URL shown. Enter a test message and select Send. When done, select Close Socket. The Communication Log section reports each open, send, and close action as it happens.
:::image source="~/fundamentals/websockets/_static/end.png" alt-text="Final state of webpage after WebSockets connection and test messages are sent and received":::
:::moniker-end