In ASP.NET Core 10, why does a synchronous Request.Body read throw on Kestrel, and why is Request.Form still risky although it does not throw?
answer
- AllowSynchronousIO defaults to false
- "Synchronous operations are disallowed"
- IHttpBodyControlFeature per request
- ReadForm calls ReadFormAsync().GetAwaiter().GetResult()
- await Request.ReadFormAsync(ct)
basics
~10 sKestrel's AllowSynchronousIO defaults to false, so a synchronous body Read throws InvalidOperationException. Request.Form never touches that guard: it reads the form asynchronously and blocks on the result, which is sync-over-async. Use await Request.ReadFormAsync().
solid answer
~40 sAll server I/O in ASP.NET Core is asynchronous, so Kestrel, IIS and HTTP.sys default `AllowSynchronousIO` to `false`. A synchronous `Request.Body.Read`, a `StreamReader.ReadToEnd()` over the body or a synchronous `Response.Body.Write` throws `InvalidOperationException`: "Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead." Setting it to `true` (on `KestrelServerOptions` or per request through `IHttpBodyControlFeature`) does not make the read synchronous underneath: Kestrel then calls `ReadAsync(...).GetAwaiter().GetResult()`, so you have opted in to sync-over-async. `HttpRequest.Form` is the quieter trap: its getter calls `FormFeature.ReadForm()`, which runs `ReadFormAsync().GetAwaiter().GetResult()`. The body is read with async APIs, so the guard never fires, but the request thread is blocked while a slow client uploads. Call `await Request.ReadFormAsync(ct)` first; reading `Request.Form` afterwards just returns the cached form.
code
csharp · 12 linesapp.MapPost("/manifests", async (HttpRequest request, CancellationToken ct) =>
{
// reads the multipart body without blocking a thread
var form = await request.ReadFormAsync(ct);
var carrierId = form["carrierId"].ToString();
var file = form.Files.GetFile("manifest");
return file is null
? Results.BadRequest()
: Results.Accepted($"/manifests/{carrierId}");
});go deeper
Remember that body reads and writes must be async, and that ReadFormAsync is the method to use for forms.
Explain AllowSynchronousIO and its default, the exception it throws, and why Request.Form blocks without throwing.
Find hidden synchronous body access in middleware and libraries, and contain any unavoidable case with async buffering and size limits.
Decide whether AllowSynchronousIO may ever be enabled in a service and how such exceptions are reviewed and tracked.
## The guard: AllowSynchronousIO ASP.NET Core's servers implement request and response bodies as `Stream`s, and `Stream` has both `Read` and `ReadAsync`. The servers themselves only do asynchronous I/O, so offering a synchronous `Read` would mean blocking a thread on asynchronous work. To stop that by default, every in-box server has an **`AllowSynchronousIO`** option, and its default is **`false`**: | Server | Option | Default | |---|---|---| | Kestrel | `KestrelServerOptions.AllowSynchronousIO` | `false` | | IIS in-process | `IISServerOptions.AllowSynchronousIO` | `false` | | HTTP.sys | `HttpSysOptions.AllowSynchronousIO` | `false` | With the default, a synchronous read of the request body or a synchronous write to the response body throws `InvalidOperationException` with the message "Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead." (or `WriteAsync` for writes). Typical triggers: - `new StreamReader(Request.Body).ReadToEnd()`; - an older serializer that only reads synchronously from the body stream; - `Response.Body.Write(...)` in custom middleware. ## Turning it on, and what that really means You can allow synchronous I/O globally with `builder.WebHost.ConfigureKestrel(o => o.AllowSynchronousIO = true)`, or for one request through the **`IHttpBodyControlFeature`**: ```csharp var bodyControl = context.Features.Get<IHttpBodyControlFeature>(); if (bodyControl is not null) bodyControl.AllowSynchronousIO = true; ``` That removes the exception, not the cost. In the ASP.NET Core 10 source, Kestrel's request stream implements `Read` as `ReadAsync(...).GetAwaiter().GetResult()` once the guard is passed. The thread is blocked for as long as the client takes to send the body, which on a slow mobile connection can be seconds. Treat the per-request switch as a narrow, documented escape hatch for a synchronous-only library, never as a global default. ## The quieter trap: Request.Form `HttpRequest.Form` is a synchronous property, and it **does not throw**. Its getter calls `FormFeature.ReadForm()`, which: 1. returns the cached form if it has already been read; 2. throws `InvalidOperationException` if the request has no form content type; 3. otherwise calls **`ReadFormAsync().GetAwaiter().GetResult()`**. Step 3 reads the body with asynchronous APIs, so the `AllowSynchronousIO` guard never fires, but the calling thread blocks until the whole form, including any file sections, has arrived and been parsed. That is sync-over-async hidden behind a property, and it is why the ASP.NET Core best-practices guidance says to prefer `ReadFormAsync`. ## The safe patterns - In a handler or middleware, call **`await context.Request.ReadFormAsync(cancellationToken)`**. Afterwards, reading `Request.Form` is safe, because it returns the cached result. - Let the framework bind the form for you (form parameters in Minimal APIs, `[FromForm]` in MVC); framework binding reads the body asynchronously. - For JSON bodies, use `ReadFromJsonAsync<T>()` or a bound parameter instead of reading the stream into a string. - For a library that only parses synchronously, first buffer the body asynchronously (for example `await Request.Body.CopyToAsync(memoryStream)` with a size limit), then hand it the buffered copy. ## Middleware that reads the body Logging or auditing middleware often wants the raw body and then must leave it readable for the endpoint. The asynchronous way is: 1. call `context.Request.EnableBuffering()` so the body can be rewound; 2. read it with `await reader.ReadToEndAsync()` on a `StreamReader` created with `leaveOpen: true`; 3. set `context.Request.Body.Position = 0` before calling the next middleware. None of these steps needs `AllowSynchronousIO`. Middleware that instead calls `ReadToEnd()` either throws under the defaults or, if someone switched the option on to silence it, blocks a thread on every request that passes through it. ## In the freight dashboard The dashboard has a manifest-upload endpoint that posted multipart forms and read `Request.Form["carrierId"]` in the handler. It passed every test, because test clients upload instantly. In production, carriers uploading from slow links held one pool thread each for the full upload, and at the morning peak the report endpoints on the same instances starved. Replacing the property read with `await Request.ReadFormAsync(ct)` removed the blocking without any other change.
- When is reading Request.Form safe?When the form has already been read asynchronously in the same request, for example by an earlier `await Request.ReadFormAsync()` or by framework form binding. Then `ReadForm()` returns the cached `IFormCollection` without touching the body. Read cold, it falls through to `ReadFormAsync().GetAwaiter().GetResult()` and blocks.
- How do you support a library that only reads streams synchronously?Buffer the body asynchronously first, for example by copying `Request.Body` into a `MemoryStream` with `CopyToAsync` under an explicit size limit, then pass the buffered stream to the library. Turning on `AllowSynchronousIO` instead would block a thread for as long as the client takes to upload.
- Setting AllowSynchronousIO to true makes Kestrel read the body truly synchronously with no cost.
- Request.Form is safe because it does not trigger the AllowSynchronousIO exception.
- AllowSynchronousIO defaults to true on Kestrel and false only on IIS.
- StreamReader.ReadToEnd on Request.Body is fine for small JSON bodies under Kestrel's defaults.
- Synchronous body reads only hurt when the request body is large.