In ASP.NET Core 10, how do you accept a raw WebSocket without SignalR, and why must the handler stay running until it closes?
answer
- a middleware, a check, an upgrade
- UseWebSockets is not added for you
- context.WebSockets.IsWebSocketRequest
- AcceptWebSocketAsync returns Task<WebSocket>
- the request IS the connection
basics
~10 sCall app.UseWebSockets(), then in the endpoint check context.WebSockets.IsWebSocketRequest and await AcceptWebSocketAsync() to get a WebSocket. The handler must await its receive/send loop, because returning ends the request and tears the socket down.
solid answer
~40 s`app.UseWebSockets()` adds the middleware that puts an `IHttpWebSocketFeature` on upgrade-capable requests; `WebApplication` does not add it for you. In the endpoint (say `app.Map("/bids", ...)` for a live auction feed) check `context.WebSockets.IsWebSocketRequest`, answer an ordinary request with 400, and otherwise `await context.WebSockets.AcceptWebSocketAsync()`, which completes the upgrade and returns a `System.Net.WebSockets.WebSocket`. From then on the request *is* the connection: the handler must `await` a loop that receives and sends until the close handshake, because once it returns the response completes and a later send fails with a `WebSocketException` wrapping an `ObjectDisposedException`. If another component does the pushing, hand it a `TaskCompletionSource` and await its task. On Kestrel without `UseWebSockets`, `IsWebSocketRequest` is false and `AcceptWebSocketAsync` throws `NotSupportedException`.
code
csharp · 20 linesvar builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseWebSockets(); // not added by WebApplication
app.Map("/bids", async (HttpContext context) =>
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
using var socket = await context.WebSockets.AcceptWebSocketAsync();
// Returns only after the close handshake: the request lives as long as the socket.
await BidFeed.RunAsync(socket, context.RequestAborted);
});
app.Run();go deeper
Recall the three steps: UseWebSockets, the IsWebSocketRequest check, and awaiting AcceptWebSocketAsync, then explain that the handler must await its loop until the socket closes.
Explain why the request and socket share one lifetime, what exception an early return produces, and how a TaskCompletionSource keeps the request open while another component sends.
Show you have debugged the early-return ObjectDisposedException, know the request timeout is disabled after accept, and can say when a raw socket beats SignalR for a given client.
Frame raw WebSockets as owning everything SignalR would give you: protocol, fan-out, reconnection, scale-out; weigh that build cost against the control it buys.
## What "raw WebSockets" means in ASP.NET Core ASP.NET Core can serve a WebSocket endpoint **without SignalR's hub layer**. You get a `System.Net.WebSockets.WebSocket` object and nothing else: no hub methods, no groups, no reconnection, no message protocol. Your code decides what a message means, when to send, and when to close. That is the right trade when the client is not a SignalR client (an exchange gateway, an IoT device, a browser page speaking a fixed JSON protocol) or when you want full control of every byte, for example a feed of **live auction bids** pushed to bidders' browsers. Three pieces make it work: 1. **The middleware** (`app.UseWebSockets()`), from `Microsoft.AspNetCore.WebSockets`, which ships in the shared framework. 2. **The check** (`context.WebSockets.IsWebSocketRequest`). 3. **The accept** (`await context.WebSockets.AcceptWebSocketAsync()`), which returns `Task<WebSocket>`. ## Step 1: register the middleware `WebSocketMiddleware` looks at each request. If the server offers an upgrade (`IHttpUpgradeFeature` for HTTP/1.1, `IHttpExtendedConnectFeature` for HTTP/2), it sets an `IHttpWebSocketFeature` on `HttpContext.Features`. That feature is what `HttpContext.WebSockets` (a `WebSocketManager`) consults. - `WebApplication` adds routing and endpoint execution automatically, but **not** `UseWebSockets`; you call it yourself, before the endpoints that accept sockets run. - Options go in a `WebSocketOptions` instance passed to `UseWebSockets(options)`, or through `builder.Services.AddWebSockets(o => ...)`. - On Kestrel without the middleware, no feature is set: `IsWebSocketRequest` returns `false` and `AcceptWebSocketAsync` throws `NotSupportedException("WebSockets are not supported")`. ## Step 2: check and accept A WebSocket endpoint still receives ordinary requests, such as a crawler or someone opening the URL in a browser tab. So the handler checks `IsWebSocketRequest` first and answers anything else with `400 Bad Request`. Calling `AcceptWebSocketAsync` on a non-WebSocket request through the middleware throws `InvalidOperationException("Not a WebSocket request.")`. `AcceptWebSocketAsync` writes the handshake response (101 on HTTP/1.1, 200 on HTTP/2), disables the request timeout if the request-timeouts middleware set one, and wraps the upgraded transport in a server-side `WebSocket`. Overloads take a sub-protocol string or a `WebSocketAcceptContext` (per-socket keep-alive, compression). ## Step 3: keep the request alive This is the step candidates miss. In ASP.NET Core **the HTTP request and the WebSocket share one lifetime**. When your handler's `Task` completes, the pipeline unwinds, the response is finished and the transport is released. So: - `await` the receive/send loop inside the handler, and return only after the close handshake (or after the socket faulted). - If a background component (a bid broadcaster, a `BackgroundService`) writes to the socket, create a `TaskCompletionSource`, give it to that component together with the socket, and `await tcs.Task` in the handler; the component calls `TrySetResult()` when it is done. - Never `Task.Wait()` or `.Result` on that loop: a blocked thread-pool thread per connection starves the server. If you return early, the next send fails with a `WebSocketException` whose inner exception is an `ObjectDisposedException` ("Cannot write to the response body, the response has completed"). ## When something else does the sending Often the code that produces messages is not the handler: a bid service raises an event, or a hosted service polls a feed. The socket still has to stay inside a live request, so the handler hands the socket away and waits on a signal: ```csharp var socket = await context.WebSockets.AcceptWebSocketAsync(); var finished = new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsAsynchronously); bidPublisher.Attach(socket, finished); // calls finished.TrySetResult(null) when the socket is done await finished.Task; // the request stays open until then ``` The same rule applies in an MVC controller action: `HttpContext.WebSockets` works identically there, and the action must not return until the code using the socket has finished. ## Typical mistakes and what they cause | Mistake | Symptom | |---|---| | No `app.UseWebSockets()` | `IsWebSocketRequest` is always false; accept throws `NotSupportedException` | | No `IsWebSocketRequest` check | plain GETs reach `AcceptWebSocketAsync` and throw `InvalidOperationException` | | Loop started with `Task.Run`, handler returns | sends fail with `ObjectDisposedException` inside `WebSocketException` | | Blocking with `.Wait()` | thread-pool starvation as connections grow | | `MapGet` for the route | HTTP/2 WebSockets (CONNECT) never match the endpoint | ## Where it fits Raw WebSockets are the low-level option. If you need fan-out to groups, automatic transport fallback, reconnection or typed client calls, that is what SignalR adds on top; when you choose raw sockets you build any of that you need yourself.
- What does the string you pass to AcceptWebSocketAsync(subProtocol) do?It picks the sub-protocol the server agrees to speak. The client offers names, which you read from `context.WebSockets.WebSocketRequestedProtocols`; you pass one of them to `AcceptWebSocketAsync("bids.v1")` and the middleware echoes it in the handshake response. Passing a name the client never offered is a protocol error the client will reject, so choose from the offered list or pass none.
- Can you accept a raw WebSocket inside an MVC controller action instead of a Minimal API endpoint?Yes. The action uses `HttpContext.WebSockets` exactly the same way: check `IsWebSocketRequest`, `await AcceptWebSocketAsync()`, then `await` the loop before the action returns, because returning early ends the request and kills the socket. Route the action with `[Route("/bids")]` rather than `[HttpGet]` so HTTP/2 CONNECT requests reach it.
- WebApplication registers the WebSocket middleware automatically, so UseWebSockets is optional.
- Start the socket loop with Task.Run and return from the handler straight away.
- AcceptWebSocketAsync can be called on any request; the IsWebSocketRequest check is cosmetic.
- Use Task.Wait() on the loop to keep the request open without async code.
- A raw WebSocket endpoint gives you SignalR's groups and reconnection for free.