while we thrive for cloud storage with large no of files and storage with low cost, we find cloudflare as good solution with no engress fee. With single engress fee only, the monthly cost can be huge difference.
nuget package: NuGet Gallery | CloudFlareR2Storage 1.0.0
What we will do?
- Upload files to our cloudflare r2 storage via token
- use custom domain cdn to display files in web page
What’s required?
- cloudflare account with r2 storage
- r2 bucket
- generate api token for respective bucket
- assign custom domain for respective bucket
appSettings.json
"R2Settings": {
"AccessKeyId": "<access-id>",
"SecretAccessKey": "<secret-key>",
"BucketName": "<bucket-name>",
"Endpoint": "https://<account-id>.r2.cloudflarestorage.com"
}
program.cs
// Bind R2Settings from appsettings.json
builder.Services.Configure<R2Settings>(builder.Configuration.GetSection("R2Settings"));
// Register the R2StorageService
builder.Services.AddTransient<R2StorageService>(sp =>
{
var r2Settings = sp.GetRequiredService<IOptions<R2Settings>>().Value;
return new R2StorageService(
r2Settings.AccessKeyId,
r2Settings.SecretAccessKey,
r2Settings.BucketName,
r2Settings.Endpoint
);
});
in file upload controller
string org_menu_path = $"org_{data.OrganizationId}/MenuItem/";
data.CloudR2ImagePath = await r2Service.UploadFileFromDiskAsync(org_menu_path, data.ImagePath);