aws / aws/aws-lambda-dotnet

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

Open
#1,185 3 comments 2 reactions 0 assignees View on GitHub
bug module/aspnetcore-support needs-investigation p2 queued
Dominant language
C#
Stars
1.7k
Forks
503
Avg merge
1d 5h
Merged PRs (30d)
18

Description

### 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:

```csharp
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.