I have an endpoint in my .NET 8 web api that I want to use to return 1 to 1 the contents of an S3 object which is a JSON file.

Using AWSSDK.S3, the request returns a response object with a stream to read the content. What would be the correct/most performant and memory efficient way to return that JSON file to my API's clients?

I have this so far:

app.MapGet("/timezones", async () =>
{
    var request = new GetObjectRequest
    {
        BucketName = Environment.GetEnvironmentVariable("S3_BUCKET_NAME"),
        Key = "allData.json",

    };
    var response = await s3Client.GetObjectAsync(request);
    return Results.Stream(
        async (stream) =>
        {
            try
            {
                await response.ResponseStream.CopyToAsync(stream);
            }
            finally
            {
                response.Dispose();
            }
        },
        "application/json"
    );
});

Thanks.

1

There are 1 best solutions below

0
On

Just use Results.Stream accepting the stream:

app.MapGet("/timezones", async () =>
{
    // ...
    return Results.Stream(response, contentType: "application/json");
});

It automatically dispose the stream for you after serving the result (source).

Or just perform redirect if the S3 object is accessible by the client (and you are ok with making the link public).