Skip to content

File storage ​

One page for every option

This page covers every choice of --Persistence, --Auth, --IncludeTests and --Aspire. A label says which options a part is for; the copy in your app's docs/ folder has only yours. ApiHost stands for your app's name.

Files people upload (pictures, attachments, imports) go through one interface, IFileStorage (src/ApiHost/Storage/). It has three implementations, and configuration chooses one, so features don't change when you move from a single server to a cloud provider:

Storage:ProviderWhere files goSuits
Local (the default)A folder on the server (Storage:Local:RootPath)One app on one server, such as the setup in deploy/
S3Any store with the S3 API: AWS S3, Cloudflare R2, Backblaze B2, Wasabi, Hetzner, DigitalOcean Spaces, Scaleway, OVH, Google Cloud Storage, or self-hosted SeaweedFS, Garage, Ceph or RustFSFiles off the server, more than one instance, a CDN
AzureBlobAzure Blob StorageApps on Azure

All three are free, open-source code: AWS's SDK (Apache-2.0) for S3 and Microsoft's (MIT) for Azure. The providers themselves charge for storage, except the self-hosted ones.

How uploads work ​

Browsers upload and download directly with short-lived signed URLs, so large files never pass through the app:

  1. The browser asks one of your endpoints to upload. The endpoint checks the user may, picks the file's key, and returns CreateUploadUrlAsync(key, contentType, lifetime): a URL and the headers to send.
  2. The browser PUTs the file to that URL with those headers.
  3. The browser tells your endpoint it's done. The endpoint checks the file with GetInfoAsync (size, content type) before using it, and deletes it if it doesn't qualify. S3 and Azure can't limit a signed upload's size, so this check is what enforces your limits.

Download a file with a URL from CreateDownloadUrlAsync(key, fileName, lifetime). On every provider the browser saves it as an attachment named fileName (Content-Disposition: attachment, signed into the URL), so an uploaded HTML page or SVG drawing is never opened as a page on the store's address, where it could pose as your app. An <img> still shows a picture from it. Files the app writes itself (such as a resized picture) go through SaveAsync; OpenReadAsync, GetInfoAsync and DeleteAsync do the rest.

Todo attachments are the worked example (Features/Todos/TodoAttachments.cs and TodoAttachmentEndpoints, and useAttachFile in the client's features/todos/todoQueries.ts). They add what a real feature needs around the three steps:

  • An upload token. Step 1 returns, with the URL, the file's key, name and type encrypted with Data Protection, and step 3 takes it back, so the browser can't change what it's finishing or where it goes. It expires with the URL.
  • Limits checked twice: the size the browser declares before the upload, and the stored size after it (Attachments:MaxBytes, 25 MB by default; Attachments:MaxPerTodo, 10).
  • Abandoned uploads cleaned up. Starting an upload schedules DeleteAttachmentIfUnused for after the token expires, which deletes the file unless it was attached by then. Removing an attachment sends the same message, so the file goes once the change is saved.
  • Downloads by short-lived link: the browser can't send the access token with a plain link, so it asks the API for a 5-minute download URL, then follows it.

Keys are paths such as organisations/{id}/logo.webp: segments of letters, digits, ., _ and -, separated by /. The same rules apply on every provider, so a key that works locally works in production. Put the owner first (the user or organisation ID), and give keys an extension: local disk has nowhere else to keep a file's content type.

csharp
// Step 1: the browser asks to upload a report's PDF.
// (The Todo attachments show the whole flow, with its checks.)
[WolverinePost("/api/reports/{reportId}/upload")]
public static Task<SignedUpload> Post(Guid reportId, IFileStorage storage, CancellationToken cancellationToken)
    => storage.CreateUploadUrlAsync($"reports/{reportId}/{Guid.NewGuid():N}.pdf", "application/pdf", TimeSpan.FromMinutes(10), cancellationToken);

Deleting an owner's files ​

When a user, organisation or other owner is deleted, delete its files by publishing DeleteStoredFiles with its prefix from the handler that deletes its data, as Pictures/PictureCleanup.cs does for AccountDeleted:

csharp
public static ValueTask Handle(AccountDeleted message, IMessageContext context)
    => context.PublishAsync(new DeleteStoredFiles($"users/{message.UserId}/"));

Don't call IFileStorage in that handler. Wolverine runs every handler of one message as one chain, with one transaction and one retry policy, so a storage outage there would fail every feature's clean-up with it. DeleteStoredFiles is sent only once the data is deleted, and retried on its own (after 1 minute, 10 minutes, 1 hour and 6 hours) until the store answers. Publish it; don't return it from the handler: a message returned by one handler of a combined chain was dropped, along with the whole chain's work (see the note in Storage/DeleteStoredFiles.cs).

For a single file that's been replaced, delete it in the background the same way, once the change is saved, and check first that nothing uses it any more (DeletePictureIfUnused is an example).

Local disk ​

Files go under Storage:Local:RootPath (data/files in the app's folder by default, relative to it unless absolute, with or without a trailing /; src/ApiHost/data/files/ is in .gitignore). Signed URLs point at the app itself (/api/files), with the key, the operation and the expiry encrypted in the URL by ASP.NET Core Data Protection. Storage:Local:MaxUploadBytes (25 MB by default) caps each upload.

Downloads come from the app's own address, so a stored HTML page or SVG drawing could run scripts as the app if a browser opened it. Besides coming as an attachment, as on every provider, each download is sent with Content-Security-Policy: default-src 'none'; sandbox, so nothing in it can run even if it's opened anyway.

In a container, put the folder on a volume, or files disappear with the container. deploy/docker-compose.yml mounts the app-files volume at /app/data; back it up with the database (see deploy/README.md). Local disk only works with one instance of the app: with more, use S3 or Azure.

S3-compatible storage ​

SettingValue
Storage__ProviderS3
Storage__S3__ServiceUrlThe store's endpoint. Leave empty for AWS itself
Storage__S3__RegionAWS: the bucket's region. R2: auto. Others: whatever they document (often us-east-1)
Storage__S3__BucketThe bucket, which must already exist
Storage__S3__AccessKey, Storage__S3__SecretKeyAn access key for the bucket. On AWS you can leave them empty to use an instance or task role
Storage__S3__ForcePathStyletrue for most self-hosted stores (the bucket goes in the path, not the host name)

Some examples:

ProviderServiceUrlRegion
AWS S3(empty)eu-west-1
Cloudflare R2https://<account-id>.r2.cloudflarestorage.comauto
Backblaze B2https://s3.<region>.backblazeb2.com<region>, such as eu-central-003
Hetznerhttps://<location>.your-objectstorage.com<location>, such as fsn1
Google Cloud Storagehttps://storage.googleapis.comauto
SeaweedFS, Garage, Ceph, RustFSYour server, such as https://s3.example.comus-east-1 (with ForcePathStyle=true)

Google Cloud Storage speaks the S3 API through its XML API: create an HMAC key for a service account (Cloud Storage → Settings → Interoperability) and use it as the access key. Signed uploads, downloads and the rest of IFileStorage work; some S3 features this app doesn't use (such as multipart upload details) differ.

The app turns off the checksums that the AWS SDK adds to every request by default since 2025, which many S3-compatible stores reject.

Azure Blob Storage ​

SettingValue
Storage__ProviderAzureBlob
Storage__AzureBlob__ConnectionStringThe storage account's connection string, with its key (signed URLs are signed with it)
Storage__AzureBlob__ContainerThe container (files by default); created on first use

Azure doesn't speak the S3 API, so it has its own implementation. Signed URLs are SAS URLs.

Let browsers reach the store (CORS) ​

With S3 or Azure, the browser uploads straight to the store, from your app's address. The store must allow that, or the browser blocks the upload. The app's Content-Security-Policy already allows the store's address. Allow PUT and GET from your app's address, with any headers:

  • S3-compatible stores: a CORS rule on the bucket, in the provider's dashboard or with aws s3api put-bucket-cors --bucket <bucket> --endpoint-url <ServiceUrl> --cors-configuration '{"CORSRules":[{"AllowedOrigins":["https://app.example.com"],"AllowedMethods":["PUT","GET"],"AllowedHeaders":["*"],"MaxAgeSeconds":3600}]}'.
  • Azure: Storage account → Resource sharing (CORS) → Blob service, or az storage cors add --services b --methods GET PUT --origins https://app.example.com --allowed-headers '*' --max-age 3600 --connection-string "<connection string>".

Trying each provider locally ​

docker compose --profile storage up -d starts SeaweedFS (S3, on port 8333) and Azurite (Azure, on port 10000). Then run the API with one of:

bash
# S3 (SeaweedFS allows any origin, so no CORS rule is needed)
Storage__Provider=S3 Storage__S3__ServiceUrl=http://localhost:8333 Storage__S3__Bucket=files \
Storage__S3__AccessKey=dev-access-key Storage__S3__SecretKey=dev-secret-key Storage__S3__ForcePathStyle=true \
dotnet run --project src/ApiHost

# Azure (Azurite's well-known development account)
Storage__Provider=AzureBlob \
Storage__AzureBlob__ConnectionString="UseDevelopmentStorage=true" \
dotnet run --project src/ApiHost

For browser uploads to Azurite, add a CORS rule for http://localhost:5173 with the az command above and the same connection string.

With the tests

Tests ​

tests/ApiHost.Tests/FileStorageTests.cs runs the same tests against every provider: local disk through the app, S3 against SeaweedFS and Azure against Azurite, each in a container. If you write your own implementation (for example for another cloud), add a class that inherits FileStorageContract and it gets the same tests.

Documentation for v0.9.0. Released under the MIT licence.