Reading the request body of HttpRequest only retrieves 4,019 characters

I have a .NET Core web application that reads information that is posted from other computer. The transmitted information is more than 4,019 characters.
I created this extension method in my application:
public static async Task<string> GetContentBody(this HttpRequest? request)
{
if (request == null)
return string.Empty;
request.Body.Position = 0;
var reader = await request.BodyReader.ReadAsync();
var buffer = reader.Buffer;
try
{
return Encoding.Default.GetString(buffer.FirstSpan).Trim();
}
finally
{
request.BodyReader.AdvanceTo(buffer.End);
}
}
This extension method is intended to get all content that was send using POST method from other computer.
The problem, when there are more than 4,019 characters, only the first 4,019 are retrieved.
This is very curious for me, but maybe there some explanation on this behaviour and a possible solution.
Also, I have this in Program.cs:
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
Jaime
Answer
Problem was finally because Span/ReadOnlySpan
cannot be used in async methods. So I modified extension method to this one:
public static async Task<string> GetContentBody(this HttpRequest? request)
{
if (request == null)
return string.Empty;
StringBuilder sb = new();
request.Body.Position = 0;
while (true)
{
var reader = await request.BodyReader.ReadAsync();
var buffer = reader.Buffer;
try
{
if (reader.IsCompleted && buffer.Length > 0)
{
AddStringToReturn(sb, buffer);
}
}
finally
{
request.BodyReader.AdvanceTo(buffer.Start, buffer.End);
}
if (reader.IsCompleted)
{
break;
}
}
return sb.ToString();
}
private static void AddStringToReturn(StringBuilder sb, in ReadOnlySequence<byte> readOnlySequence)
{
// Separate method because Span/ReadOnlySpan cannot be used in async methods
ReadOnlySpan<byte> span = readOnlySequence.IsSingleSegment ? readOnlySequence.FirstSpan : readOnlySequence.ToArray().AsSpan();
sb.Append(Encoding.Default.GetString(span).Trim());
}
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions