This commit is contained in:
saingchildren 2026-04-23 18:01:37 +08:00
parent f801f35fd7
commit af5f578f83
5 changed files with 56 additions and 1 deletions

View File

@ -11,6 +11,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.Extensions.NETCore.Setup" Version="4.0.3.34" />
<PackageReference Include="AWSSDK.S3" Version="4.0.22" />
<PackageReference Include="Microsoft.AspNetCore.SpaProxy">
<Version>8.*-*</Version>
</PackageReference>

View File

@ -0,0 +1,33 @@
using Amazon.S3;
using Microsoft.AspNetCore.Mvc;
namespace AWS_Practice.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ImagesController : ControllerBase
{
private readonly IAmazonS3 _s3;
private readonly string _bucket;
public ImagesController(IAmazonS3 s3, IConfiguration configuration)
{
_s3 = s3;
_bucket = configuration["AWS:BucketName"]!;
}
[HttpGet("{*key}")]
public async Task<IActionResult> Get(string key, CancellationToken ct)
{
try
{
var response = await _s3.GetObjectAsync(_bucket, key, ct);
return File(response.ResponseStream, response.Headers.ContentType ?? "application/octet-stream");
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return NotFound();
}
}
}
}

View File

@ -1,3 +1,7 @@
using Amazon;
using Amazon.Runtime;
using Amazon.S3;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
@ -7,6 +11,14 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IAmazonS3>(_ =>
{
var aws = builder.Configuration.GetSection("AWS");
return new AmazonS3Client(
new BasicAWSCredentials(aws["AccessKey"], aws["SecretKey"]),
RegionEndpoint.GetBySystemName(aws["Region"]));
});
var app = builder.Build();
app.UseDefaultFiles();

View File

@ -4,5 +4,9 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AWS": {
"AccessKey": "",
"SecretKey": ""
}
}

View File

@ -5,5 +5,9 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"AWS": {
"Region": "us-east-1",
"BucketName": "saingchildren-s3"
}
}