Skip to content

Duplicate response body when running on Lambda and manipulating response body stream in middleware #1185

Open
@madmox

Description

@madmox

Describe the bug

I have a ASP.NET middleware which temporarily replaces the HTTP response body stream with a memory stream so that it can perform work involving seek operations on the response stream before the response is sent to the client. The code works properly when running locally using Kestrel or the integration tests server, but when running on AWS, all response bodies are duplicated (i.e. {"foo":"bar"} becomes {"foo":"bar"}{"foo":"bar"}).

Expected Behavior

The response should be a valid JSON result on all hosting environments (e.g. {"foo":"bar"}).

Current Behavior

The response is invalid when running on AWS Lambda only (duplicated JSON, e.g. {"foo":"bar"}{"foo":"bar"}).

Reproduction Steps

Simplified middleware code looks like this:

public async Task InvokeAsync(HttpContext context)
{
    Stream originalResponseBodyStream = context.Response.Body;
    using var buffer = new MemoryStream();
    context.Response.Body = buffer;

    try
    {
        await this._next(context);
        // Do work involving seek on body stream
    }
    finally
    {
        context.Response.Body.Seek(0, SeekOrigin.Begin);
        await context.Response.Body.CopyToAsync(originalResponseBodyStream);
        context.Response.Body = originalResponseBodyStream;
    }
}

Possible Solution

No response

Additional Information/Context

My ASP.NET application is using the Minimal API hosting pattern. The AWS Lambda hosting mode is set to LambdaEventSource.RestApi.

AWS .NET SDK and/or Package version used

  • Amazon.Lambda.AspNetCoreServer 7.1.0
  • Amazon.Lambda.AspNetCoreServer.Hosting 1.1.0

Targeted .NET Platform

.NET 6

Operating System and version

AmazonLinux

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions