Storage & video with ASP.NET Core

Audience: .NET developers who store files, upload them, deliver them and play video through plycdn from an ASP.NET Core backend. This guide takes you from an empty project to uploads, signed links, video playback and webhooks. Your backend holds the plycdn API key and decides who may do what; browsers (Angular, React, or your own code) call your backend, never plycdn directly. The browser side is in Storage & video with Angular and Storage & video with React. What each call returns, field by field, is in the Storage and Video guides and the API reference.

1Install the packages

Download the packages from your dashboard: Developers → SDKs, where each language is its own download: pick .NET.

There is one package per purpose, so you install only what you use. All of them target .NET 6 to 10.

Package What it gives you
Plycdn.AspNetCore.Storage Buckets, custom domains, uploads, signed links, cache purges, usage and audit from your server (PlycdnStorageApi, PlycdnUploader, PlycdnLinkSigner), and the routes your frontend calls (PlycdnStorageController, at api/plycdn/v1).
Plycdn.AspNetCore.Video Video libraries, videos, playback links, webhooks (PlycdnVideoApi, PlycdnVideoSigner, PlycdnWebhookVerifier) and the video route (PlycdnVideoController). Builds on Storage.
Plycdn.AspNetCore.Storage.S3 An S3 client configured for a plycdn region, for tools and pipelines.
Plycdn.AspNetCore.Storage.AzureBlob An Azure Blob client configured for your storage account.

Install from the plycdn feed. Add a nuget.config beside your solution (commit it, so your colleagues and CI need no setup). The source mapping sends every Plycdn.* package to the plycdn feed and everything else to nuget.org:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
    <add key="plycdn" value="https://nuget.plycdn.com/v3/index.json" />
  </packageSources>
  <packageSourceMapping>
    <packageSource key="plycdn"><package pattern="Plycdn.*" /></packageSource>
    <packageSource key="nuget.org"><package pattern="*" /></packageSource>
  </packageSourceMapping>
</configuration>
dotnet add package Plycdn.AspNetCore.Storage
dotnet add package Plycdn.AspNetCore.Video      # only if you use video

For use with a plycdn account under the plycdn Terms of Use: https://plycdn.com/terms. The feed has every version from Storage & video 1.22.0 onward; earlier versions stay available as downloads in your dashboard under Developers → SDKs. Step by step, with checks and fixes: Install the SDKs.

Or download the packages from Developers → SDKs, unzip them into ./vendor/nuget and add --version 1.21.0 --source ./vendor/nuget to each command.

Plycdn.AspNetCore.Video depends on Plycdn.AspNetCore.Storage, so installing Video alone is enough for video. These packages are independent of Plycdn.ContentSearch.AspNetCore: use either, or both in one application.

2Configure

Add a Plycdn section to your server configuration. Keep the API key in your secret store (user secrets, environment variables, your host's secret manager), never in source control and never in a browser bundle:

{
  "Plycdn": {
    "ApiKey": "<server API key>",
    "OrganizationClaimType": "plycdn_organization_id"
  }
}
Setting Default Meaning
ApiBaseUrl https://api.plycdn.com/ The address of the API. Leave it out unless your plycdn contact gives you another HTTPS address.
ApiKey none Your server's API key, from the dashboard. A standard key does everything a running service needs; creating, changing and deleting buckets, libraries, domains and webhooks needs an admin key (admin_key_required otherwise). Keep the admin key in the automation that sets things up.
OrganizationClaimType plycdn_organization_id The claim on your signed-in user that holds their plycdn organization id. The browser never chooses an organization.
SigningProfileCacheFor 1 hour How often the link signer checks a bucket's signing settings for a change (at least 5 minutes). It keeps them until they change; the check downloads nothing when nothing changed.
MaxBrowserLinkTtl none The longest lifetime your browser sign route will issue (at least 60 seconds).
CompatDomain plycdn.net The domain of the storage hosts. Leave it as it is unless plycdn tells you otherwise.

If your servers restrict outbound traffic, allow api.plycdn.com on port 443.

A key made for one organization (the default Reach when you create a key) needs the id of that organization and no other: pass it as the organization id to every call (the OrganizationClaimType claim on your user supplies it for the browser routes). Calls for another organization of your account are refused with organization_out_of_key_reach (403). A key that reaches the whole account serves any of your organizations. See Give a key to one organization only.

3Register the services

Register storage, or video (which registers storage as well), in an authenticated host, and keep MapControllers():

using Plycdn.AspNetCore.Storage;
using Plycdn.AspNetCore.Video;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddPlycdnVideo(builder.Configuration);          // storage and video
// builder.Services.AddPlycdnStorage(builder.Configuration);    // storage only
builder.Services.AddScoped<IPlycdnStorageAuthorizer, CourseFilesAuthorizer>();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Calling AddPlycdnStorage and AddPlycdnVideo together is harmless. Both have an overload that takes an Action<PlycdnOptions> when you configure in code. Registration adds PlycdnStorageApi, PlycdnUploader, PlycdnLinkSigner and the browser routes, and with video PlycdnVideoApi and PlycdnVideoSigner; inject what you need. The sign route (POST api/plycdn/v1/sign) signs a link to a stored file (objectId) of a private files bucket in your server, without calling plycdn; links by file name (key), videos and live inputs work as before. Locally signed links take their expiry from your server's clock, so keep it synchronised.

4Decide who may do what

The browser routes under api/plycdn/v1 are refused for everyone until you register an IPlycdnStorageAuthorizer. Every request asks it about one operation, on one bucket, and where it applies one key (a file's key; for video, the video id). The organization always comes from the signed-in user's OrganizationClaimType claim.

PlycdnOperation Asked for key
ListObjects listing a bucket's files the prefix, if any
GetObject reading one file the file's key
StartUpload starting an upload the key it will have
ContinueUpload renewing, completing, aborting or reading an upload the upload's key
Sign getting a signed link for a file the file's key
GetVideo reading a video (title, status, captions) the video id
WatchVideo getting a playback link, for a video or for a live input the video id, or the live input id
using System.Security.Claims;
using Plycdn.AspNetCore.Storage;

public sealed class CourseFilesAuthorizer : IPlycdnStorageAuthorizer
{
    public Task<bool> AuthorizeAsync(ClaimsPrincipal user, PlycdnOperation operation, Guid bucketId,
                                     string? key, CancellationToken cancellationToken) =>
        Task.FromResult(operation switch
        {
            PlycdnOperation.ListObjects or PlycdnOperation.GetObject or PlycdnOperation.Sign
                or PlycdnOperation.GetVideo or PlycdnOperation.WatchVideo => user.IsInRole("learner"),
            _ => user.IsInRole("instructor"),
        });
}

Going live from a browser is decided apart, by an IPlycdnLiveAuthorizer (Live streaming): being allowed to watch never lets anyone broadcast.

Make the decision from your own data: which course a bucket belongs to, whether the user is enrolled, and so on. A refusal answers 403 {"code":"forbidden"} and reveals nothing about the file.

Two things to know about proxies and viewers. For a bucket that binds links to the viewer's address, the sign route signs for the request's remote address, which must be IPv4: behind a load balancer, configure ASP.NET Core's forwarded headers so that address is the viewer's. With no address, or an IPv6 one, the route answers 422 validation_error rather than issue a link the delivery network would refuse. And a cross-origin frontend needs your own CORS policy for the plycdn routes, as for any other API of yours.

5Buckets and server uploads

From server code, inject PlycdnStorageApi (calls), PlycdnUploader (uploads) and PlycdnLinkSigner (links):

using Plycdn.AspNetCore.Storage;

public sealed class CourseMedia
{
    private readonly PlycdnStorageApi api;
    private readonly PlycdnUploader uploader;
    private readonly PlycdnLinkSigner signer;

    public CourseMedia(PlycdnStorageApi api, PlycdnUploader uploader, PlycdnLinkSigner signer)
    { this.api = api; this.uploader = uploader; this.signer = signer; }

    public async Task<Uri> PublishAsync(Guid orgId, Stream file, long length)
    {
        // Admin key. A bucket's name is global, like an S3 bucket's: choose one that is yours.
        var bucket = await api.CreateBucketAsync(orgId, new BucketCreate("acme-course-media", "mumbai"));

        // Server to server: plans the parts, uploads them with retries, completes the session.
        StoredObject stored = await uploader.UploadAsync(orgId, bucket.Id, "week-1/intro.mp4", file, length, "video/mp4");

        return await signer.SignAsync(orgId, bucket.Id, stored.Key, TimeSpan.FromMinutes(15));
    }
}

Region codes are strings from ListRegionsAsync; treat them as data. Bucket.State is creating until the bucket is active (poll GetBucketAsync), and BucketCreate also takes Visibility (private by default, or public), StrictResidency, Delivery, UploadRules, Cache and Cors. Other calls on PlycdnStorageApi include ListBucketsAsync, UpdateBucketAsync, DeleteBucketAsync, RestoreBucketAsync, ListObjectsAsync, GetObjectAsync, DeleteObjectAsync, the domain calls (CreateDomainAsync, CheckDomainAsync, ListDomainsAsync), PurgeCacheAsync, GetDeliveryAnalyticsAsync, GetUsageByResourceAsync, GetAuditAsync and GetStorageRequestsAsync.

GetStorageRequestsAsync(organizationId, StorageRequestQuery? query) answers one page of what your S3 and Azure tools sent, refused requests included, as a StorageRequestPage (Items, NextCursor, RetentionDays). StorageRequestQuery has From, To, Bucket, Credential, AccessKey, Account, Operation, Status, Code, RequestId, KeyPrefix, ClientIp, Organization, Cursor and Limit. ListStorageRequestsAsync returns an IAsyncEnumerable<StorageRequest> over every page. request_log_unavailable reports Retryable = true. See Check that requests reach plycdn.

When you hand the bytes of a file to a browser to upload, you do not use PlycdnUploader: the browser packages upload straight to the bucket's region with a short-lived ticket, and your backend only relays the control calls through the controller. Use PlycdnUploader when your own server holds the bytes (an import, a migration, a nightly job).

An organization can hold at most 1,000 open uploads at once; one more fails with plan_limit_reached (403) until one completes, is aborted or expires. A session left open (an interrupted UploadAsync, whose PlycdnException carries UploadId, or one you started with CreateUploadAsync) counts until it expires after 7 days: abort the ones you will not resume (AbortUploadAsync).

Disaster-recovery copies and locations. ListRegionsAsync returns each location's StorageOnly, ProcessingCountry and DrTargets. GetBucketReplicationAsync(organizationId, bucketId), EnableBucketReplicationAsync(organizationId, bucketId, region) and DisableBucketReplicationAsync(organizationId, bucketId) keep, read and remove a bucket's copy in a second location (admin key to turn on or off). Deleting a file deletes it from the copy too. See Keep a disaster-recovery copy and Choose where files live.

Searching your own storage

GetBucketSearchAsync, UpdateBucketSearchAsync and RemoveBucketFromSearchAsync on PlycdnStorageApi read, change and clear a bucket's (or a video library's) search switch; the settings are a BucketSearch (Enabled, Folder, Access, Slides, Language, and IncludePastRecordings for a library), also taken as Search on BucketCreate, BucketPatch, CreateLibraryRequest and UpdateLibraryRequest. A Bucket, a StoredObject and a Video carry Search (state, reason, asset id). Changing the switch and removing from search need an admin key. The Content Search package adds GetPlaybackAsync (a link for a file that came from your own bucket or library), GetActivityForBucketAsync, and Source on ContentAsset, ContentActivity and ContentSearchResult. Its browser controller's assets/{id}/source plays files of your own buckets and libraries with no ICustomerFileStorage call. See Make a bucket searchable.

6Signed links

A public bucket serves its files at https://<bucket>.plycdn.net/<key> with no signing. A private bucket needs a signed link, which PlycdnLinkSigner makes in your own process from the bucket's cached signing profile, with no request to plycdn per link:

Uri link = await signer.SignAsync(orgId, bucketId, "week-1/intro.mp4", TimeSpan.FromMinutes(15));
// Write the link out with link.AbsoluteUri: it keeps the key's percent-encoding.

PlycdnLinkSigner and PlycdnVideoSigner sign plycdn links (pl1, and pl1d for a whole video) in your process from Storage & video 1.4.0; earlier versions ask plycdn to sign them (/sign), so they keep working unchanged.

A link lasts 60 seconds to 7 days (the bucket's linkTtlSeconds when you leave the lifetime out). For a bucket with IP binding pass the viewer's IPv4 address. To serve a bucket on your own domain, add the domain, create the DNS records it lists at your DNS host, and sign on it:

var domain = await api.CreateDomainAsync(orgId, new DomainCreate(bucketId, "media.example.com"));
// domain.Records: the TXT (ownership) and CNAME (routing) records to create at your DNS host
domain = await api.CheckDomainAsync(orgId, domain.Id);          // check now rather than wait

Uri onDomain = await signer.SignAsync(orgId, bucketId, "week-1/intro.mp4",
    new PlycdnSignOptions { Ttl = TimeSpan.FromMinutes(15), Hostname = "media.example.com" });

PlycdnSignOptions carries the lifetime (Ttl), the viewer's address (Ip), the hostname and Tags. A hostname that is neither the bucket's default nor one of its active domains is refused with domain_not_active (409). The signer checks against the settings it keeps: a domain that has just become active is found by one extra fetch (at most one a minute per bucket); after deleting a domain, call signer.Forget(orgId, bucketId) so this process stops signing on it. Under invariant globalization pass a Unicode hostname in its xn-- form (domain.Hostname). If you would rather have plycdn sign for you, api.SignAsync(orgId, new SignRequest(bucketId, Key: "week-1/intro.mp4")) does it over HTTP.

When the signing settings change

The signer fetches a bucket's or library's signing settings once and keeps them until they change. It learns of a change in four ways:

  • A rotation from this server. RotateSigningKeyAsync (admin key) refreshes every signer registered by the same AddPlycdnStorage or AddPlycdnVideo, so there is nothing to do.
  • Your webhook. Subscribe an endpoint to signing_profile.changed (Signing settings changed in the dashboard). PlycdnWebhookVerifier.ReadAsync (in Plycdn.AspNetCore.Video) refreshes the registered signer when that event arrives, so a rotation, domain or link-setting change made in the dashboard or from another server applies at once. If you read events another way (or use Plycdn.AspNetCore.Storage alone), pass them on with signer.HandleWebhook(organizationId, type, data).
  • A refused link. When our players ask for a new link because the last one was refused, the sign route fetches the settings again (at most 3 times per bucket or library in 10 minutes).
  • An hourly check (SigningProfileCacheFor), which downloads nothing when nothing changed.

Without a webhook, a change made elsewhere reaches this server within about an hour; call signer.Forget(orgId, bucketId) or restart to pick it up at once. Rotating a key invalidates every link signed with the old one.

Tags and delivery analytics

PlycdnSignOptions.Tags labels a link so delivery analytics can break traffic down by it, for example by the customer a viewer belongs to:

Uri link = await signer.SignAsync(orgId, bucketId, "week-1/intro.mp4",
    new PlycdnSignOptions { Tags = new Dictionary<string, string> { ["customer"] = "acme" } });

Up to 8 tags per link; a name is a lower-case letter then lower-case letters, digits and underscores (32 characters at most), a value 1 to 128 bytes without control characters or any of &, =, ? and #. The signer refuses anything else with an ArgumentException naming the tag. Until link tags are enabled for your account (the signing profile's TagsEnabled), the signer refuses any tag with PlycdnException validation_error, detail "Link tags are not available yet; sign the link without tags", exactly as the service does; links without tags are unaffected. Tags are for private buckets (a public bucket's links are not signed: a request to sign one with tags is refused with 422 validation_error) and are not available on video playback links (also refused). A viewer who edits a tag in a link is counted as (unverified).

For links your browsers ask for through the sign route, tags the browser sends are ignored by default, so visitors cannot label their own links as someone else. Set them from your signed-in user with PlycdnOptions.TagsFor, or, if the labels are harmless to you, set PlycdnOptions.AcceptBrowserTags = true:

builder.Services.AddPlycdnStorage(o =>
    o.TagsFor = (http, request) => new Dictionary<string, string> { ["customer"] = http.User.FindFirst("customer")!.Value });

Turn analytics on and choose breakdowns with BucketPatch.Analytics (BucketAnalyticsPatch: Enabled, Dimensions of AnalyticsRule, Ceiling; ClearAnalyticsCeiling returns the ceiling to your plan's), on a library with UpdateLibraryRequest.Analytics. Read the results with an admin key: GetDeliveryAnalyticsSeriesAsync (over time), GetDeliveryBreakdownAsync (a month, by organization or by a breakdown's values) and GetDeliveryBreakdownCsvAsync (the same month as a stream of CSV; dispose the stream), and try a rule on recent traffic with PreviewAnalyticsRuleAsync. A bucket's Analytics shows Enabled, Dimensions, Ceiling, EffectiveCeiling and Since. The routes, answers and errors (too_many_rows, export_busy, too_many_organizations, analytics_unavailable) are in the Storage guide and the API reference.

7Video

Video builds on storage: a library is a private bucket made for video. You create a library once, then create a video for each recording; plycdn encodes it into adaptive streaming and tells your backend when it is ready. Register AddPlycdnVideo (above) and inject PlycdnVideoApi and PlycdnVideoSigner.

Libraries and videos

Creating a library needs an admin key. A video is created before its file is uploaded; the answer carries the upload session to hand to the browser, and the video goes uploading → queued → encoding → playable → ready (or failed, with an ErrorCode):

using Plycdn.AspNetCore.Video;

var library = await videos.CreateLibraryAsync(orgId, new CreateLibraryRequest("acme-lectures", "mumbai"));

var created = await videos.CreateVideoAsync(orgId, library.Id,
    new CreateVideoRequest("Week 1: Introduction", Size: fileSize, ContentType: "video/mp4", FileName: "week-1.mp4"));
// created.Id is the video; created.Upload is the session. Return it to the browser, which uploads the
// parts and completes the upload through your controller. Completing it moves the video to "queued".

CreateLibraryRequest also takes Processing (the quality ladder, whether to keep the original, downloads and thumbnails), Delivery and MaxObjectBytes. If your server holds the files, PlycdnVideoUploader does it for you: UploadVideoAsync(organizationId, libraryId, path, title) creates the video and uploads its file (resumed and retried), and UploadVideosAsync(organizationId, libraryId, folder) uploads every video file of a folder under sources/, four at a time, skipping the ones already added (and any file starting with a dot or symlinked), so a second run carries on after an interruption; each VideoUploadResult has File, Key, VideoId, Skipped and Error (UploadVideosOptions sets Concurrency and Progress). PlycdnVideoUploader comes with AddPlycdnVideo. ContinueUploadAsync (on PlycdnUploader) sends an upload session you already started (the Upload of CreateVideoAsync), and GetVideoBySourceKeyAsync (on PlycdnVideoApi) finds the video a file under sources/ became.

Read a video with GetVideoAsync, list a library's with ListVideosAsync(orgId, libraryId, status: "failed"), change a title or metadata with UpdateVideoAsync and remove one with DeleteVideoAsync.

Leave Processing out and the library uses your organization's video settings; a sub-organization uses its parent's unless it sets its own, higher or lower. Set them with VideoDefaults (Ladder, KeepOriginal, Download, Thumbnails) when you change settings with UpdateSettingsAsync, and read them, with where each value comes from, from GetSettingsAsync. A library's Processing is null when it uses its organization's settings, and updating a library with Processing null returns it to them. ReencodeVideoAsync(orgId, videoId) encodes a ready video again with the settings that apply now (original_not_kept when its original was not kept); the video's Encoding says what it was made with.

Playback

The player in your pages asks your backend for two things, both authorized by your IPlycdnStorageAuthorizer: GET api/plycdn/v1/videos/{id} (the video, PlycdnOperation.GetVideo) and POST api/plycdn/v1/sign with a videoId (a playback link, PlycdnOperation.WatchVideo). Both pass the library as bucketId and the video id as key; the browser packages make these calls for you.

To make a link yourself, sign it in your own process:

PlaybackLink link = await videoSigner.SignVideoAsync(orgId, library.Id, video.Id, TimeSpan.FromHours(4));
// link.Url: the stream, for your player. link.NativeUrl: for players that play adaptive streams natively, or null.
// link.ExpiresAt, link.PosterUrl, link.ThumbnailsUrl, link.DownloadUrl.

Signed locally, PosterUrl, ThumbnailsUrl and DownloadUrl are always set: use them only when video.Poster, video.Thumbnails and video.Download say the file exists. Signing locally does not check that the video exists or can play yet; the sign route does, and answers video_not_ready or video_not_found when that matters. The expiry comes from this server's clock, so keep it synchronised (NTP).

videoSigner.SignVideoFromPlycdnAsync (same arguments) always asks plycdn instead. Use it for the recording of a live stream that may be protected: only plycdn's answer carries link.Protection (how a player gets the keys to play it), and a link signed locally has none. The video player (<plycdn-player>, PlycdnPlayer) does not play protected video in this release; the Integration guide says how to play a protected recording.

Serial playback

A library with serial playback lets no viewer reach a moment sooner than that much time after they started watching (Serial playback; step by step in the Serial playback guide). The players need no change; your server names each viewer with your own id for them (a learner or a seat, never an email address), the same id on every visit:

builder.Services.AddPlycdnStorage(o =>
    o.PlaybackResumeIdFor = (http, library, video) => http.User.FindFirst("learner")?.Value);

From your own code, with PlycdnVideoApi:

  • StartPlaybackAsync(orgId, new PlaybackSessionRequest(libraryId, videoId) { ResumeId = "learner-42" }) starts a session and returns the playback link with Serial, WatchedSeconds, DurationSeconds, Completed, Pass and ProgressUrl.
  • GetPlaybackProgressAsync(orgId, libraryId, videoId, resumeId) reads how far one viewer has watched one video (progress_not_found before they start it).
  • ListPlaybackProgressAsync(orgId, libraryId, resumeId) lists every video of the library they have started, a page at a time.
  • ResetPlaybackProgressAsync(orgId, libraryId, videoId, resumeId) starts them over for a retake; their watch time is kept.
  • GetWatchTimeReportAsync(orgId, libraryId, new WatchTimeQuery { From = new DateOnly(2026, 10, 1), To = new DateOnly(2026, 10, 31) }) reads the library's watch time per viewer (or per video with GroupBy, for one viewer with ResumeId, for one video with VideoId), a page at a time with NextCursor (GetWatchTimeItemsAsync reads every row as an IAsyncEnumerable); DownloadWatchTimeCsvAsync(orgId, libraryId, query) returns the same range as a CSV stream. Progress answers carry WatchTimeSeconds and FirstWatchedAt, and a started session ProgressIntervalSeconds and WatchTimeSeconds. See Watch time per viewer.

In a serial library the signing calls of PlycdnVideoSigner (SignVideoAsync) refuse with serial_playback_requires_session; use StartPlaybackAsync instead. The sign route of your backend starts the session for you, in every library: once your PlaybackResumeIdFor returns an id, ordinary libraries record watch time too.

A library can draw each viewer's details over its videos, and your logo in a corner, in every plan (Viewer watermark and player logo; step by step in the watermark guide). The players draw them; your server says who is watching with PlaybackWatermarkFor, beside PlaybackResumeIdFor:

builder.Services.AddPlycdnStorage(o =>
    o.PlaybackWatermarkFor = (http, organization, library, video) =>
        ValueTask.FromResult<PlycdnWatermarkViewer?>(new PlycdnWatermarkViewer
        {
            Name = http.User.Identity?.Name,
            Email = http.User.FindFirst("email")?.Value,
            ViewerId = http.User.FindFirst("student_id")?.Value,
        }));

The settings, with PlycdnVideoApi and an admin key:

await videos.UpdateWatchBrandAsync(orgId, new UpdateWatchBrandRequest
{
    Watermark = new UpdateWatermarkSettings { Mode = WatermarkModes.Show, Fields = new[] { "name", "email", "time" }, Text = "Example Academy" },
    PlayerLogo = new UpdatePlayerLogoSettings { Enabled = true, Position = "bottom-right" },
});
await videos.UpdateLibraryAsync(orgId, libraryId, new UpdateLibraryRequest { Watermark = new UpdateWatermarkSettings { Mode = WatermarkModes.Require } });
await videos.UpdateLibraryAsync(orgId, libraryId, new UpdateLibraryRequest { UseBrandWatermark = true });           // the organization's again
await videos.UpdateLibraryAsync(orgId, libraryId, new UpdateLibraryRequest { Logo = new LibraryLogo(LibraryLogo.Off) });
  • The route sends the details only when the browser says it draws the watermark ("watermark": "drawn", as the React and Angular players do); a library that requires it answers 409 watermark_required to any other request, without calling plycdn. A property you leave null is left out; return null for a visitor you can't name. Look (a PlycdnWatermarkLook: Opacity, Size, Color, MoveEverySeconds or StaysPut, Placement such as PlycdnWatermarkPlacement.In("top-left", "bottom-right")) changes the look for one viewer.
  • The ip line is sent only for libraries that bind links to the viewer's address; PlaybackSessionRequest.Ip sets it yourself.
  • Library.Watermark is the library's own settings (null while it uses the organization's), Library.Logo its LibraryLogo, and Library.EffectivePlayer what its viewers get. WatchBrand.Watermark and PlayerLogo are filled with WatermarkSettings.Defaults and PlayerLogoSettings.Defaults until saved; ClearWatermark and ClearPlayerLogo return them to the defaults.
  • A player of your own: StartPlaybackAsync(orgId, new PlaybackSessionRequest(libraryId, videoId) { Watermark = viewer }) answers SessionId, RenewBy, Watermark and Logo. PlycdnWatermark.Render(session) gives what to draw (Required, Lines, TimeAt, Opacity, Size, Color, MoveEverySeconds, Placement, Proof, ProofEverySeconds), LinesAt(viewerTime) inserts the time and CheckIn(intact) is the check-in's watermark; PlycdnWatermark.Renewal(request, session) is the renewal (keep the same viewer). After watermark_proof_invalid or watermark_tampered (403) stop; only after playback_session_expired (410) start a new session.
  • In a library that requires the watermark, SignVideoAsync throws PlycdnException watermark_required (409), and SigningProfile.RequiresWatermark is true.

Live streaming

Live inputs, stream keys, publish tokens and streams are on PlycdnVideoApi (admin key, on your server); playback links for a running stream are PlycdnVideoSigner.SignLiveAsync. What live streaming is, and how to choose between its two delivery modes, is in the Video guide.

using Plycdn.AspNetCore.Video;

// Once, from your setup code or a back office: a place to broadcast to. The key is shown here (and by RevealStreamKeyAsync).
LiveInputCreated input = await videos.CreateLiveInputAsync(orgId, library.Id, new CreateLiveInputRequest("Main stage",
    new LiveInputSettings { Delivery = DeliveryMode.Realtime, Quality = "hd", LatencyTarget = LatencyTarget.Lowest }));
await secrets.SaveAsync(quot;plycdn-live-{input.Id}", input.StreamKey);
// input.Ingest.Rtmps / Rtmp / Srt go into the encoder; input.Ingest.Whip is the browser address.

LiveInput now = await videos.GetLiveInputAsync(orgId, input.Id);          // now.State, now.Stream?.Health
await videos.UpdateLiveInputAsync(orgId, input.Id, new UpdateLiveInputRequest(Settings: new LiveInputSettings { Recording = false }));
LiveInputCreated replaced = await videos.RotateStreamKeyAsync(orgId, input.Id);   // the old key stops working at once
await videos.DisableLiveInputAsync(orgId, input.Id);                      // ends a running stream: input_disabled
await videos.EndStreamAsync(orgId, input.Id);                             // live_not_started when none is running
StreamPage page = await videos.ListStreamsAsync(orgId, input.Id, limit: 20);  // page.Items, page.NextCursor
LiveStream stream = await videos.GetStreamAsync(orgId, page.Items[0].Id); // State, EndReason, Health, RecordingId

CreateLiveInputAsync, UpdateLiveInputAsync, DeleteLiveInputAsync, RotateStreamKeyAsync, RevealStreamKeyAsync, CreatePublishTokenAsync, DisableLiveInputAsync, EnableLiveInputAsync, EndStreamAsync, ListLiveInputsAsync, ListStreamsAsync and GetStreamAsync need an admin key. A refusal is a PlycdnException; PlycdnLiveErrors holds its codes (LiveInputNotFound, LiveNotStarted, LiveInputDisabled, LiveInputBusy, LiveCapReached, LiveQuotaExceeded, PublishTokenInvalid, StreamKeyInUse, FeatureNotAvailable, FeatureNotInPlan); for live_cap_reached the cap is named in the error's detail. Settings you leave null are not sent; LiveInput.Settings always carries them all.

More settings and calls. LiveInputSettings also takes BackupIngest, RedundantTranscoding, Captions (LiveCaptionSettings: Enabled, Languages, Mode CaptionModes.Realtime or CaptionModes.NearLive), DvrWindowSeconds (0 to 7,200; 0, the default, offers no rewind), IndexRecording, Protection (LiveProtectionSettings) and Ads (LiveAdsSettings). With backup ingest on, LiveIngest.RtmpsBackup, RtmpBackup and SrtBackup are the backup encoder's addresses, usually on their own host name (backup-{label}.live.plycdn.com): give them to the encoder as they are.

LiveStreamCaptions captions    = await videos.GetStreamCaptionsAsync(orgId, stream.Id);   // languages and mode
LiveStreamViewers viewers      = await videos.GetStreamViewersAsync(orgId, stream.Id);    // peak, watch time, countries; BroadcastCounted
LiveStreamHealthHistory health = await videos.GetStreamHealthAsync(orgId, stream.Id, stepSeconds: 300);

// Restreaming and ad breaks, when your plan includes them.
LiveDestination partner = await videos.CreateDestinationAsync(orgId, input.Id,
    new CreateDestinationRequest("Partner site", "rtmps://live.partner.example/app", partnerKey));   // sends an Idempotency-Key; pass idempotencyKey: to retry
DestinationTestResult test = await videos.TestDestinationAsync(orgId, partner.Id);                  // test.Reachable; nothing is published
IReadOnlyList<LiveDestination> all = await videos.ListDestinationsAsync(orgId, input.Id);           // State, LastError (LiveDestinationErrors)
await videos.UpdateDestinationAsync(orgId, partner.Id, new UpdateDestinationRequest(Key: newKey));
await videos.DeleteDestinationAsync(orgId, partner.Id);
LiveAdBreak adBreak = await videos.InsertAdBreakAsync(orgId, input.Id, new InsertAdBreakRequest(DurationSeconds: 30));
IReadOnlyList<LiveAdBreak> breaks = await videos.ListAdBreaksAsync(orgId, input.Id, limit: 20);      // newest first; State includes cancelled
await videos.CancelAdBreakAsync(orgId, input.Id, adBreak.Id);       // planned and more than 45 s away, else ad_break_not_cancellable (409)
IReadOnlyList<ProtectionSetup> setups = await videos.ListProtectionSetupsAsync(orgId);              // the names LiveProtectionSettings.Provider takes

All of these need an admin key. Their refusals are in PlycdnLiveErrors too: LiveSettingNotInPlan, LiveSettingConflict (ads with protection, ads with a rewind window), ProtectionNotConfigured, DestinationUnreachable, DestinationLimitReached, DestinationUrlInvalid, DestinationNotFound and RateLimited. The Video guide explains each feature.

Going live from the browser. Register an IPlycdnLiveAuthorizer. The controller route POST api/plycdn/v1/live-inputs/{id}/publish-token asks it before it makes a token, and the default refuses everyone:

public sealed class StageCrewAuthorizer(ICrew crew) : IPlycdnLiveAuthorizer
{
    public Task<bool> AuthorizeGoLiveAsync(ClaimsPrincipal user, Guid liveInputId, Guid libraryId, CancellationToken ct) =>
        crew.CanBroadcastAsync(user, liveInputId, ct);
}
builder.Services.AddSingleton<IPlycdnLiveAuthorizer, StageCrewAuthorizer>();

To make a token yourself: PublishToken token = await videos.CreatePublishTokenAsync(orgId, input.Id, TimeSpan.FromMinutes(15)); (1 second to 1 hour; the service default is 15 minutes when you pass none through the controller). token.Token and token.WhipUrl go to the browser; never send the stream key.

Playing. The browser routes are GET api/plycdn/v1/live-inputs/{id} (only the input's id, state, delivery and the stream's id, state and times; authorizer operation PlycdnOperation.GetVideo) and POST api/plycdn/v1/sign with a liveInputId and an optional mode (PlycdnOperation.WatchVideo, the live input's id as the key). From your own code:

LivePlaybackLink link = await videoSigner.SignLiveAsync(orgId, library.Id, input.Id, DeliveryMode.Broadcast, ttl: TimeSpan.FromMinutes(15));
// Broadcast: link.Url (low latency), link.FallbackUrl (standard). Real-time: link.WhepUrl, with link.Url for overflow.
// link.Mode is Broadcast when the input's own mode is broadcast, or when real-time was asked and its cap or capacity was reached. Tags and a hostname are refused on live links (422 tags_not_on_live, hostname_not_on_live). link.Latency, link.StreamId, link.ExpiresAt.
// Where they apply: link.Realtime (Kind whep or rtc, Url, Token), link.Captions (Language, Url), link.DvrWindowSeconds, link.Ads (SessionId), link.Protection.

It throws a PlycdnException with Code live_not_started (409, Retryable true) while nothing is streaming; ask again in a few seconds. The ttl is 60 seconds to 7 days, and ip is the viewer's IPv4 address for a library with IpBinding.

Share links. A share link lets anyone watch an input with no account (Share a live stream). The four calls need an admin key:

ShareLink link = await videos.CreateShareLinkAsync(orgId, input.Id, new CreateShareLinkRequest(
    Label: "Town hall", Password: "meeting-2026", ExpiresAt: DateTimeOffset.UtcNow.AddDays(7), ShowRecording: true));   // link.Url, link.HasPassword
IReadOnlyList<ShareLink> links = await videos.ListShareLinksAsync(orgId, input.Id);                                   // newest first
await videos.UpdateShareLinkAsync(orgId, input.Id, link.Id, new UpdateShareLinkRequest { Disabled = true });           // off; false turns it back on
await videos.UpdateShareLinkAsync(orgId, input.Id, link.Id, new UpdateShareLinkRequest { ClearPassword = true, ClearExpiresAt = true, ClearLabel = true });
await videos.DeleteShareLinkAsync(orgId, input.Id, link.Id);

CreateShareLinkRequest takes Label, Password, ExpiresAt, ShowRecording and, for this link only, Title, Description, Messages (WatchMessages) and Layout (WatchLayouts) (all optional). In UpdateShareLinkRequest a field left null is unchanged, and the ClearLabel, ClearPassword, ClearExpiresAt, ClearTitle, ClearDescription, ClearMessages and ClearLayout flags remove that value (a value and its flag together throw ArgumentException). ShareLink carries Id, LiveInputId, Url, Label, Urls (every address that opens it: Url, then one per active watch domain), Title, Description, Messages and Layout (null when the link follows the brand), HasPassword (the password is never read back), ExpiresAt, ShowRecording, Disabled, CreatedAt and UpdatedAt. The refusals are PlycdnLiveErrors.ShareLinkNotFound (404) and ShareLinkLimitReached (409, detail.limit); a retried create makes a second link. Viewers' refusals on the public watch routes (WatchLinkNotFound, WatchNotStarted, WatchEnded, WatchPasswordRequired, WatchPasswordAttempts) are also in PlycdnLiveErrors, for code of your own that calls them (API reference).

Watch page brand and your own domains. The look of the pages share links open, and hostnames of yours to open them on (Brand your watch page, Use your own domain for watch pages). All of these need an admin key:

WatchBrand brand = await videos.GetWatchBrandAsync(orgId);                                   // brand.Inherited: a sub-organization showing its account's
await videos.UpdateWatchBrandAsync(orgId, new UpdateWatchBrandRequest
{
    AccentColor = "#c2410c", Layout = WatchLayouts.SidePanel, Title = "Acme Summit", SiteUrl = "https://acme.example/",
    Messages = new WatchMessages(Starting: "Doors open soon"), FooterLinks = new[] { new WatchFooterLink("Privacy", "https://acme.example/privacy") },
    ClearBackgroundColor = true,                                                             // back to the theme's own background
});
await videos.UploadWatchBrandLogoAsync(orgId, File.OpenRead("logo.png"), "image/png");       // PNG, JPEG or WebP, up to 512 KB
await videos.DeleteWatchBrandLogoAsync(orgId);

WatchDomain domain = await videos.AddWatchDomainAsync(orgId, "watch.example.com");           // domain.CnameTarget, domain.Verification.Records (TXT and CNAME)
WatchDomain now = await videos.GetWatchDomainAsync(orgId, domain.Id);                        // State, FailureReason, Verification.Checks
IReadOnlyList<WatchDomain> domains = await videos.ListWatchDomainsAsync(orgId);
await videos.RemoveWatchDomainAsync(orgId, domain.Id);

In UpdateWatchBrandRequest a field left null is unchanged and its Clear… flag (ClearAccentColor, ClearBackgroundColor, ClearTheme, ClearLayout, ClearTitle, ClearDescription, ClearMessages, ClearSiteUrl, ClearSiteLabel, ClearFooterLinks, ClearLogoSize) returns it to the built-in value; a value and its flag together throw ArgumentException. Messages and FooterLinks are sent whole. WatchLayouts (Cinema, Standard, SidePanel), WatchThemes (Dark, Light) and WatchLogoSizes (Small, Medium, Large) hold the words; LogoSize is on both the brand you read and the request you send (null on the brand means Small). The refusals are in PlycdnLiveErrors: LogoInvalid, LogoTooLarge, WatchDomainLimitReached, WatchDomainNotFound, DomainExists and HostnameNotAllowed.

Events. PlycdnWebhookVerifier.LiveConnected, LiveStarted, LiveDisconnected, LiveEnded, LiveFailover, LiveDestinationFailed and LiveAdBreak name the events and PlycdnWebhookEvent.AsLive() reads one into a LiveEventData (LiveInputId, StreamId; with live.ended EndReason and DurationSeconds; with live.failover From and To; with live.destination_failed DestinationId, Name and Error; with live.ad_break BreakId, DurationSeconds and StartedAt). The recording is the video whose id is the stream's id: GetVideoAsync(orgId, stream.Id).

Webhooks

Webhooks tell your backend when a video is playable, ready or failed, and how a live broadcast is going, so you do not poll. Create an endpoint once (admin key); the secret is shown once, so keep it in your secret store:

var hook = await videos.CreateWebhookAsync(orgId,
    new CreateWebhookRequest(new Uri("https://api.example.com/plycdn"), new[] { "video.ready", "video.failed" }, "LMS"));
await secrets.SaveAsync("plycdn-webhook", hook.Secret);        // your own secret store
await videos.PingWebhookAsync(orgId, hook.Id);                  // sends a webhook.ping to try it

Receive them with PlycdnWebhookVerifier, which reads the body, checks the signature and parses the event. Always verify before acting: anyone can send a request to your URL.

app.MapPost("/plycdn", async (HttpRequest request, IOptions<MySecrets> secrets, Lessons lessons) =>
{
    PlycdnWebhookEvent evt;
    try { evt = await PlycdnWebhookVerifier.ReadAsync(request, secrets.Value.WebhookSecrets); }
    catch (PlycdnWebhookSignatureException) { return Results.Unauthorized(); }

    // An event can arrive more than once: act once per delivery.
    if (!await lessons.FirstTimeAsync(request.Headers["Plycdn-Delivery"].ToString()))
        return Results.Ok();

    if (evt.Type == "video.ready" && evt.AsVideo() is { } video)
        await lessons.PublishAsync(video.Id);
    return Results.Ok();
});

secrets.Value.WebhookSecrets is a list so that you can hold the new and the previous secret while you rotate (RotateWebhookSecretAsync). PlycdnWebhookVerifier.Verify(body, signatureHeader, secrets) does the same over bytes you already hold. To see what was delivered, ListWebhookDeliveriesAsync(orgId, hook.Id, state: "failed") and RedeliverWebhookAsync(orgId, deliveryId). Return a 2xx quickly; plycdn retries anything else.

8Observability

We recommend Logthread, our observability product (billed on its own), for your applications' logs, metrics and traces: see Logthread for ASP.NET Core. This section covers plycdn's built-in observability.

PlycdnObservabilityApi (in Plycdn.AspNetCore.Storage, registered with AddPlycdnStorage or AddPlycdnVideo) sends nothing: your applications send logs, metrics and traces to plycdn with an ingest key (Observability). From your server you manage that, and read the data back. Every call needs an admin API key (admin_key_required with a standard one), so inject it only where the admin key lives; QueryTelemetryAsync, ValidateTelemetryQueryAsync, GetTelemetryReferenceAsync, ExportTelemetryAsync, TailLogsAsync and GetTraceAsync also accept a read-only query key (plyq_…) as the ApiKey setting. To get your first data in, follow the quick start; to instrument an ASP.NET Core application without changing its code, see OpenTelemetry with no code change. Needs Plycdn.AspNetCore.Storage 1.14.0 or later.

using Plycdn.AspNetCore.Storage;

public sealed class Telemetry(PlycdnObservabilityApi observability)
{
    public async Task SetUpAsync(Guid orgId)
    {
        // Once: choose the region (it cannot change), how long to keep data, and optionally a bucket of your own to archive into.
        await observability.UpdateObservabilitySettingsAsync(orgId, new ObservabilitySettingsUpdate { Region = "mumbai", RetentionDays = 90 });

        // One key per application or customer of yours. The key is in this answer only.
        IngestKeyCreated key = await observability.CreateIngestKeyAsync(orgId, new IngestKeyCreate("checkout-service"));
        // key.Key = "plyt_..."; ObservabilitySettings.Endpoints says where to send data.
    }

    public async Task<TelemetryResult> ErrorsByServiceAsync(Guid orgId) =>
        await observability.QueryTelemetryAsync(orgId, new TelemetryQuery
        {
            Sql = "SELECT ServiceName, count() AS errors FROM obs.logs WHERE Timestamp >= {from:DateTime64(3)} AND SeverityNumber >= {level:UInt8} GROUP BY ServiceName",
            Params = new Dictionary<string, object> { ["level"] = 17 },
            From = DateTimeOffset.UtcNow.AddHours(-6),
        });
}
  • QueryTelemetryAsync returns Columns, Rows (each value a JsonElement; a 64-bit whole number is a string: long.Parse(value.GetString()!)) and Stats. Stats has ReadBytes, ReadRows and ElapsedMs. A statement is refused with query_invalid, query_too_expensive or query_timeout (PlycdnException.Code); set MaxExecutionMs (1,000 to 30,000, up to 120,000 where your account's ceiling was raised, 1,000 to 600,000 for an export) to give it less time (validation_error outside the range). query_busy and read_quota_exceeded (429, retryable) are not sent again for you: wait PlycdnException.RetryAfter, then send the call again.
  • ExportTelemetryAsync(orgId, new TelemetryExport { Sql = ..., Format = "parquet" }) returns a Stream of the file as it is produced. A download that is cut part-way throws (a PlycdnException with code provider_unavailable, retryable, from reading the stream, as a cut tail does): the file is incomplete, so delete it and run the export again.
  • TailLogsAsync(orgId, new LogTailOptions { Service = "checkout", Severity = 17 }) is an IAsyncEnumerable<LogTailEvent> of logs events (Rows, Cursor) that stops after an end event, about five minutes in. Call it again with Cursor = lastEvent.Cursor to carry on; if the sequence ends without an end event (a dropped connection), resume from the cursor of the last event you received. Logs run about 8 seconds behind real time, and a log stamped more than a day before it arrives is stored and queryable but not tailed. A failure after the stream started throws a PlycdnException.
  • Set Dialect = "kql" on a TelemetryQuery (or TelemetryExport) to write the query in KQL (logs | where ... | summarize ...), with the same tables and limits.
  • ValidateTelemetryQueryAsync(orgId, new TelemetryQuery { ... }) returns a TelemetryValidation (Valid, Columns, Stats, or Error with Message, Line and Column) without running the query for rows; a query that does not check out is a result, not an exception. GetTelemetryReferenceAsync(orgId) returns what KQL offers (Kql.Operators, Functions, Aggregations), the Tables, the Errors and the Limits. Step by step: Observability, step by step.
  • A download's id: (stream as ExportStream)?.QueryId from ExportTelemetryAsync; FindSlowQueryAsync(orgId, queryId) returns the one statement (a SlowQueryPage) and shows what the download read, a few seconds after it ends.
  • GetSlowQueriesAsync(orgId, from, to, minDurationMs, limit, cursor) returns a SlowQueryPage (Items, NextCursor) of your own queries that took at least minDurationMs (default 1000), newest first, from the last 24 hours by default and at most 30 days back. Each SlowQuery has At, DurationMs, ReadRows, ReadBytes, ResultRows, MemoryBytes, Dialect, Failed, ErrorCode, Query (the first 4,096 characters) QueryTruncated and QueryId. Pass NextCursor back as cursor for the next page.
  • GetTraceAsync(orgId, traceId), GetTelemetryVolumesAsync(orgId, from, to) (each day has ReceivedGb, IngestedGb, Complete, Rejected and Signals.Logs, Signals.Metrics, Signals.Traces), GetObservabilitySettingsAsync(orgId), ListIngestKeysAsync(orgId) and RevokeIngestKeyAsync(orgId, keyId) do what their names say. To stop archiving, set ClearArchiveBucketId = true on ObservabilitySettingsUpdate: a bucket id and the clear flag together throw an ArgumentException.
  • CreateQueryKeyAsync(orgId, new QueryKeyCreate(name, rowFilter)) makes a read-only key for the six read calls, optionally held to a row filter built with QueryKeyRowFilter.Match, Except, AllOf and AnyOf; created.Key is in the answer only. ListQueryKeysAsync(orgId) and RevokeQueryKeyAsync(orgId, keyId) do what their names say (a tail or download the key has open is cut within 30 seconds). With a filtered key, Stats.ReadRows and Stats.ReadBytes read 0 (the service sends null). Refusals: query_key_limit_reached (409), query_key_not_found (404), and query_key_not_allowed (403) when a query key calls anything else. Step by step: Give a customer, a team or a partner access to part of your logs.
  • GetObservabilityArchivesAsync(orgId, from, to) answers what the nightly archive did, by day and kind of data (State, Key, Bytes, Rows, Sha256, Reason), with each day's Manifest; both dates are inclusive, the default is the last 30 days and the most is 92. See what the archive did.
  • Ingest keys, retention and archive: Observability.

Send plycdn's own activity to Logthread

Connect an organization to your Logthread workspace with an ingest key (in Logthread: Keys, Ingest keys), and plycdn sends that organization's storage request log, video and live events, and daily delivery totals there. The key is checked with Logthread before it is kept, and never shown again; reading the connection returns only KeyHint, its last four characters. Admin key only (GET, PUT and DELETE on /integrations/logthread). A person can also connect in one click in the dashboard (Developers → Integrations → Connect to Logthread); the connection then shows WorkspaceName (the workspace's name) and ConnectedVia is connect (key for an ingest key).

public async Task<LogthreadConnection> ConnectLogthreadAsync(PlycdnObservabilityApi observability, Guid orgId, string ingestKey)
{
    // The key is required the first time. Leave Signals null to send everything.
    await observability.ConnectLogthreadAsync(orgId, new LogthreadConnect
    {
        IngestKey = ingestKey,
        Signals = new LogthreadSignalsUpdate { Delivery = false },
    });
    return await observability.GetLogthreadConnectionAsync(orgId);   // Connected, Status, KeyHint, Signals, LastExport, LastError, ...
}
  • Status is connected, paused (Logthread asked plycdn to wait; sending resumes by itself), disconnected (Logthread refused the key; connect again with a new one) or not_connected. LastExport says when each of Storage, Video and Delivery last arrived, and LastError names the last problem in a word.
  • ConnectLogthreadAsync with only Signals changes what is sent and keeps the key. DisconnectLogthreadAsync(orgId) forgets the key; doing it twice changes nothing.
  • A key Logthread does not accept throws a PlycdnException with logthread_key_rejected (422); Logthread not answering just now throws logthread_unreachable (503, retryable): try again.

9S3 and Azure clients

Plycdn.AspNetCore.Storage.S3 and Plycdn.AspNetCore.Storage.AzureBlob build the official S3 and Azure Blob clients for plycdn, for migrations, backups and pipelines. They sign with a storage credential, created in the dashboard under Developers → Storage credentials: a server-side secret like the API key, never for a browser.

dotnet add package Plycdn.AspNetCore.Storage.S3
dotnet add package Plycdn.AspNetCore.Storage.AzureBlob
using Amazon.S3.Model;
using Plycdn.AspNetCore.Storage.AzureBlob;
using Plycdn.AspNetCore.Storage.S3;

// The host label comes from GET /regions (the region's endpoints); signing uses the region code.
using var s3 = await PlycdnS3.CreateClientAsync(api, orgId, "mumbai", accessKeyId, secretAccessKey);
await s3.PutObjectAsync(new PutObjectRequest { BucketName = "acme-course-media", Key = "notes.txt", FilePath = "notes.txt" });

var service = await PlycdnBlob.CreateServiceClientAsync(api, orgId, "acmelearning", accountKey, "mumbai");
var blob = service.GetBlobContainerClient("acme-course-media").GetBlobClient("notes.txt");
await blob.UploadAsync("notes.txt", overwrite: true);

services.AddPlycdnS3(configuration) and services.AddPlycdnBlob(configuration) register the same clients for dependency injection from the Plycdn:S3 section (Region, HostLabel, AccessKeyId, SecretAccessKey, and optionally PathStyle, which puts the bucket in the path rather than the host) and the Plycdn:Blob section (Account, AccountKey, and optionally Region with its HostLabel). You pass the region code (mumbai) and, in configuration, the host label shown in the region's endpoints in GET /regions (in-mum); the clients connect to the region's hosts (s3.in-mum.plycdn.net, <account>.blob.in-mum.plycdn.net) and sign with the code. The region code is never used as a host label: a registration without the label stops at startup with a message that names the setting, and the async CreateClientAsync / CreateServiceClientAsync read the label from GET /regions themselves, so with those HostLabel is only an override. Hosts, supported operations and limits are in the Compatibility guide.

10What your key reaches

GetAccountAsync on PlycdnStorageApi tells you what the configured key acts as and may reach: the organization, every organization it can name, the key by its prefix and scope (never the key itself), the regions with their S3 and Azure endpoints, and the products your plan includes (What your key reaches). Any key. Call it once at start-up to check the key works.

using Plycdn.AspNetCore.Storage;

public sealed class KeyCheck(PlycdnStorageApi storage)
{
    public async Task<string> DescribeAsync(Guid organizationId)
    {
        AccountSummary account = await storage.GetAccountAsync(organizationId);
        return quot;{account.Organization.Name} ({account.Reach}), key {account.Key?.Prefix} {account.Key?.Scope}, "
             + quot;{account.Organizations.Count} organizations, products: {string.Join(", ", account.Products)}";
    }
}

A key made for one organization answers for that organization and lists only it; naming another throws PlycdnException with organization_out_of_key_reach.

11Your account: sub-organizations, quotas and statements

These calls manage the sub-organizations of your account, the limits you set for each, and your monthly statements (Managing sub-organizations from code, Your quotas, Your monthly statement). Sub-organizations, the account audit and GetOrganizationQuotasAsync and SetOrganizationQuotasAsync need an admin API key that reaches the whole account (admin_key_required for a standard key, organization_out_of_key_reach for a key made for one organization), and accountId is your account's own organization id: a call made for a sub-organization is refused with organization_forbidden. GetUsageQuotasAsync and the statement calls work with any key, for the organization whose id you pass (a sub-organization's own id included), as the API reference describes.

PlycdnOrganizationApi (in Plycdn.AspNetCore.Storage, registered with AddPlycdnStorage or AddPlycdnVideo) carries them. Needs Plycdn.AspNetCore.Storage 1.16.0 or later; the Content Search package carries the same calls (PlycdnAccountApi and PlycdnContentApi), so a server already using it changes nothing.

using Plycdn.AspNetCore.Storage;

public sealed class Customers(PlycdnOrganizationApi organization)
{
    public async Task<Guid> OnboardAsync(Guid accountId, string name, string email)
    {
        PlycdnSubOrganization sub = await organization.CreateSubOrganizationAsync(
            accountId, new PlycdnSubOrganizationRequest { Name = name, ContactEmail = email });
        await organization.SetOrganizationQuotasAsync(accountId, sub.Id,
            new PlycdnOrganizationQuotasRequest { Searches = 10000, IndexGigabytes = 5 });
        return sub.Id;
    }

    public Task<string> StatementCsvAsync(Guid accountId, int year, int month) =>
        organization.ExportStatementCsvAsync(accountId, year, month);   // CSV text
}

The twelve calls are ListSubOrganizationsAsync, GetSubOrganizationAsync, CreateSubOrganizationAsync, UpdateSubOrganizationAsync, DeactivateSubOrganizationAsync, ListAccountAuditAsync, GetUsageQuotasAsync, GetOrganizationQuotasAsync, SetOrganizationQuotasAsync, ListStatementsAsync, GetStatementAsync and ExportStatementCsvAsync. Failures throw PlycdnException with the same Code and Status as the storage and video calls. In UpdateSubOrganizationAsync and SetOrganizationQuotasAsync, a property you leave out keeps its value; to remove one, set its Clear… flag (ClearSearches, and so on). Setting and clearing the same property, or changing nothing, throws an ArgumentException.

12Errors

Every refusal from plycdn is a PlycdnException with Code (the documented code, such as bucket_not_found or admin_key_required), Status (the HTTP status), Retryable and, when plycdn said so, RetryAfter. Match on Code, never on the message:

try { await api.DeleteBucketAsync(orgId, bucketId); }
catch (PlycdnException e) when (e.Code == "admin_key_required")
{
    logger.LogError("This server holds a standard key; deleting a bucket needs the admin key.");
}
catch (PlycdnException e) when (e.Retryable)
{
    await Task.Delay(e.RetryAfter ?? TimeSpan.FromSeconds(5));
    // try again
}

The codes are tabulated in the Storage, Video (the live codes are under "Live errors") and API guides. The browser routes answer the same codes, plus forbidden when your authorizer refused the request.

13Troubleshooting

  • Every browser call answers 403 forbidden. No authorizer is registered, or it returned false for that operation. The default refuses everything.
  • 403 forbidden for a signed-in user your authorizer would allow. The user has no claim named by OrganizationClaimType: with no organization there is nobody to act for, so your authorizer is not even asked. Check the claim, and that the host authenticates before MapControllers().
  • admin_key_required. The server holds a standard key for a call that needs an admin key.
  • Links stop working after a key rotation made in the dashboard or from another server. This server has not heard of it yet: subscribe a webhook to Signing settings changed (When the signing settings change), or call signer.Forget(orgId, bucketId). Without either it picks up the new key within about an hour.
  • Where do I see what happened? The dashboard's bucket and library pages show state; usage and the audit log are under Billing & usage → Usage and Account & security → Audit log.