Skip to content

Instantly share code, notes, and snippets.

@Xor-el
Created May 9, 2024 19:13
Show Gist options
  • Save Xor-el/2e4252bc305041421d564d2c7d4e0460 to your computer and use it in GitHub Desktop.
Save Xor-el/2e4252bc305041421d564d2c7d4e0460 to your computer and use it in GitHub Desktop.
ReadRequestBody
public static async Task<string?> ReadBody(this HttpRequest httpRequest, Encoding? encoding = default)
{
encoding ??= Encoding.UTF8;
// don't get it by `PipeReader.Create(httpContext.Request.Body);`
var bodyReader = httpRequest.BodyReader;
var context = httpRequest.HttpContext;
ReadResult readResult;
// read all the body without consuming it
do
{
// read sequence of bytes from the pipe reader
readResult = await bodyReader.ReadAsync(context.RequestAborted);
// Tell the PipeReader how much of the buffer we have consumed
bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
} while (!readResult.IsCanceled && !readResult.IsCompleted);
// now all the body payload has been read into buffer
var buffer = readResult.Buffer;
if (buffer.IsEmpty)
return default;
// process the buffer
return encoding.GetString(buffer);
}
public static T? ReadBody<T>(this HttpRequest httpRequest)
{
// don't get it by `PipeReader.Create(httpContext.Request.Body);`
var bodyReader = httpRequest.BodyReader;
ReadResult readResult;
// read all the body without consuming it
do
{
// try to read sequence of bytes from the pipe reader
if (!bodyReader.TryRead(out readResult))
continue;
// Tell the PipeReader how much of the buffer we have consumed
bodyReader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
} while (!readResult.IsCanceled && !readResult.IsCompleted);
// now all the body payload has been read into buffer
var buffer = readResult.Buffer;
if (buffer.IsEmpty)
return default;
// process the buffer
var reader = new Utf8JsonReader(buffer);
return JsonSerializer.Deserialize<T>(ref reader, JsonExtensions.JsonOptions);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment