Skip to content

Commit

Permalink
Fix BadHttpRequestException: Unexpected end of request content.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tsar Nikolay committed Oct 7, 2021
1 parent fe0e275 commit 8d8a420
Showing 1 changed file with 29 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ public RequestHeadersHookMiddleware(RequestDelegate next)
/// <returns>A task that can be awaited.</returns>
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}

// Skip if request has been aborted.
if (context.RequestAborted.IsCancellationRequested)
{
await _next.Invoke(context);
}

var request = context.Request;

IEnumerable<string> mimeTypeDirectives = AcceptHeaderParser.MimeTypeDirectivesFromAcceptHeader(request.Headers[HeaderNames.Accept]);
Expand All @@ -58,30 +69,34 @@ public async Task Invoke(HttpContext context)
{
request.EnableBuffering();

// Leave the body open so the next middleware can read it.
string bodyString;
using (var reader = new System.IO.StreamReader(
request.Body,
encoding: Encoding.UTF8,
detectEncodingFromByteOrderMarks: false,
bufferSize: 1024,
leaveOpen: true))
{
bodyString = await reader.ReadToEndAsync();
request.Body.Position = 0;
}
string bodyString = await GetBodyString(request);

context.Items.Add(PropertyKeyRequestContent, bodyString);
}

/*
/// Исправление для Mono, взято из https://github.com/OData/odata.net/issues/165
*/
if (!request.Headers.ContainsKey("Accept-Charset"))
request.Headers.Add("Accept-Charset", new[] { "utf-8" });
if (!request.Headers.ContainsKey(HeaderNames.AcceptCharset))
request.Headers.Add(HeaderNames.AcceptCharset, new[] { "utf-8" });

await _next.Invoke(context);
}

private static async Task<string> GetBodyString(HttpRequest request)
{
// Leave the body open so the next middleware can read it.
using var reader = new System.IO.StreamReader(
request.Body,
Encoding.UTF8,
false,
1024,
true);
string bodyString = await reader.ReadToEndAsync();
request.Body.Position = 0;

return bodyString;
}
}
}
#endif

0 comments on commit 8d8a420

Please sign in to comment.