Strange behaviour with StreamContent with Reverse Proxy redirection of HttpContext

27 views Asked by At

I'm developing Reverse Proxy inside Asp.Net Core API.

When I'm using StreamContent like this:

if (IsContentMethod(request.Method) && !string.IsNullOrEmpty(requestBody))
            {
                requestMessage.Content = new StreamContent(request.Body);
                requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
            }

I've got 'The response ended prematurely.'

But, if I just read request.Body stream as string

public static async Task<string> BodyAsStringAsync(this HttpRequest request)
        {
            if (request.ContentLength == 0)
            {
                return string.Empty;
            }

            request.Body.Seek(0, SeekOrigin.Begin);
            using var reader = new StreamReader(request.Body, leaveOpen: true);
            return await reader.ReadToEndAsync();
        }

and then just use StringContent all working as expected

if (IsContentMethod(request.Method) && !string.IsNullOrEmpty(requestBody))
            {
                requestMessage.Content = new StringContent(requestBody);
                requestMessage.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(request.ContentType);
            }

the rest of the code is absolutely equal, what could be the problem with StreamContent here?

UPDATE I found issue as I'm reading request.Body for logging purpose it set Body stream to the end, but StreamContent is just use position as is, so obviously HttpClient is trying send ended stream which is produce HttpRequestException. Problem solved.

public static async Task<string> BodyAsStringAsync(this HttpRequest request)
        {
            if (request.ContentLength == 0)
            {
                return string.Empty;
            }

            request.Body.Seek(0, SeekOrigin.Begin);
            using var reader = new StreamReader(request.Body, leaveOpen: true);
            var result = await reader.ReadToEndAsync();
            request.Body.Seek(0, SeekOrigin.Begin);
            return result;
        }
0

There are 0 answers