C# Screenshot API Tutorial: .NET 8 HttpClient, Resilience, Jobs and Webhooks
A .NET 8 guide to the Screenshotly API: a one-file quick start, a typed HttpClient with a resilience pipeline, durable jobs, signed webhooks and a Channel-based worker, all tested against a contract stub.
This guide shows how to call the Screenshotly API from C# on .NET 8. It starts with a one-file console request, then builds a typed client for ASP.NET Core: null-free JSON, typed errors, a resilience pipeline that respects Retry-After, streaming downloads, durable jobs, webhook signature checks and a background worker.
Every snippet below was built with warnings as errors and run against an offline stub that validates requests with Screenshotly's real request schema and plan rules. Nothing here depends on an unpublished SDK.
Reference docs for the .NET APIs used here: IHttpClientFactory and typed clients, Microsoft.Extensions.Http.Resilience, System.Threading.Channels and BackgroundService. For every capture parameter, see the screenshot API reference.
What you need
- The .NET 8 SDK. The code uses primary constructors, raw string literals and
HMACSHA256.HashData. - An API key from Dashboard → API Tokens, kept in user secrets, environment variables or a vault.
- A plan that covers the features you call. Free includes 100 captures in total at 5 requests per minute, with PNG, JPEG and WebP output. See pricing.
How the API works
| Endpoint | POST https://screenshotly.app/api/screenshot |
| Auth | x-api-key: YOUR_KEY header (Authorization: Bearer YOUR_KEY also works) |
| Body | JSON. Only url is required; format defaults to png |
| Success | 200 with the image or PDF bytes as the body |
| Errors | JSON {"error": "...", "message": "..."} with a 4xx or 5xx status |
| Slow work | POST https://screenshotly.app/api/jobs (Basic+) returns 202 with a job ID |
Only successful captures count against your quota.
Quick start: one console request
Create a console app (dotnet new console), replace Program.cs, and run it with SCREENSHOTLY_API_KEY set:
using System.Net.Http.Json;
var apiKey = Environment.GetEnvironmentVariable("SCREENSHOTLY_API_KEY")
?? throw new InvalidOperationException("Set SCREENSHOTLY_API_KEY first");
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) };
using var request = new HttpRequestMessage(HttpMethod.Post, "https://screenshotly.app/api/screenshot")
{
// JsonContent uses camelCase web defaults, matching the API's field names.
Content = JsonContent.Create(new { url = "https://example.com", device = "desktop", format = "png" }),
};
request.Headers.Add("x-api-key", apiKey);
using var response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
// Errors are JSON: {"error": "...", "message": "..."}
throw new HttpRequestException($"HTTP {(int)response.StatusCode}: {await response.Content.ReadAsStringAsync()}");
}
await File.WriteAllBytesAsync("screenshot.png", await response.Content.ReadAsByteArrayAsync());
Console.WriteLine("Saved screenshot.png");
JsonContent.Create uses the web serializer defaults, so property names go out in camelCase, which is what the API expects.
A typed client for ASP.NET Core
The resilience pipeline comes from one package:
dotnet add package Microsoft.Extensions.Http.Resilience
This guide was tested with version 8.10.0, which brings in Polly 8.
The request model
The API rejects unknown keys and explicit null values with 400 Invalid request data. Keep options nullable and serialize with WhenWritingNull so anything you don't set is omitted.
using System.Text.Json.Serialization;
namespace Screenshotly;
// Body for POST /api/screenshot and POST /api/jobs. Properties left null are
// omitted when serialized: the API rejects unknown keys and null values.
public sealed record CaptureRequest
{
public required string Url { get; init; }
public string Format { get; init; } = "png"; // png | jpeg | webp; pdf/html need Basic+
public string? Device { get; init; } // desktop | laptop | tablet | mobile
public int? Width { get; init; } // 320–3840
public int? Height { get; init; } // 240–3840
public bool? FullPage { get; init; }
public int? Quality { get; init; } // 0–100
public int? Delay { get; init; } // ms, 0–10000
public string? WaitForSelector { get; init; }
public bool? WaitForNetworkIdle { get; init; }
public string? Selector { get; init; }
public bool? BlockAds { get; init; }
public bool? DarkMode { get; init; }
public double? DeviceScaleFactor { get; init; } // 1–3
public string? Mockup { get; init; } // Growth+
public AiRemovalOptions? AiRemoval { get; init; } // Growth+
public IReadOnlyList<string>? HideSelectors { get; init; } // Growth+
public StorageOptions? Storage { get; init; } // Basic+
public WebhookOptions? Webhook { get; init; } // Basic+
}
public sealed record AiRemovalOptions(bool Enabled, IReadOnlyList<string> Types);
public sealed record StorageOptions(bool Enabled);
public sealed record WebhookOptions(string Url, string? Secret = null, IReadOnlyDictionary<string, string>? Headers = null);
public sealed record CaptureJob(string Id, string Status, bool? Replayed, string? StatusUrl, string? ResultUrl, string? ErrorMessage);
The record covers the options most services need. The API reference lists the rest, including clip, scroll, cookies, headers, javascript, userAgent, timezone and geolocation. Add them the same way, as nullable properties.
Typed errors
using System.Net;
using System.Text.Json;
namespace Screenshotly;
public sealed class ScreenshotlyException(HttpStatusCode status, string error, string? detail, string? minimumPlan, TimeSpan? retryAfter)
: Exception($"HTTP {(int)status} {error}{(detail is null ? "" : ": " + detail)}")
{
public HttpStatusCode Status { get; } = status;
public string Error { get; } = error;
/// <summary>Set on 403 "Plan upgrade required", e.g. "basic" or "growth".</summary>
public string? MinimumPlan { get; } = minimumPlan;
public TimeSpan? RetryAfter { get; } = retryAfter;
public static async Task<ScreenshotlyException> FromResponseAsync(HttpResponseMessage response, CancellationToken ct)
{
string error = "Unknown error";
string? detail = null, plan = null;
try
{
using var doc = JsonDocument.Parse(await response.Content.ReadAsStreamAsync(ct));
var root = doc.RootElement;
if (root.TryGetProperty("error", out var e)) error = e.GetString() ?? error;
if (root.TryGetProperty("message", out var m)) detail = m.GetString();
if (root.TryGetProperty("minimumPlan", out var p)) plan = p.GetString();
}
catch (JsonException) { /* non-JSON error body */ }
return new ScreenshotlyException(response.StatusCode, error, detail, plan, response.Headers.RetryAfter?.Delta);
}
}
The client
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Options;
namespace Screenshotly;
public sealed class ScreenshotlyOptions
{
public string BaseUrl { get; set; } = "https://screenshotly.app";
public string ApiKey { get; set; } = "";
}
public sealed class ScreenshotlyClient(HttpClient http, IOptions<ScreenshotlyOptions> options)
{
internal static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) // camelCase
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
private readonly string _apiKey = options.Value.ApiKey;
public async Task<byte[]> CaptureAsync(CaptureRequest request, CancellationToken ct = default)
{
using var response = await PostAsync("api/screenshot", request, null, ct);
return await response.Content.ReadAsByteArrayAsync(ct);
}
/// <summary>Streams the capture to disk without buffering the whole file.</summary>
public async Task CaptureToFileAsync(CaptureRequest request, string path, CancellationToken ct = default)
{
using var response = await PostAsync("api/screenshot", request, null, ct);
await using var file = File.Create(path);
await response.Content.CopyToAsync(file, ct);
}
/// <summary>Queues a durable job (Basic+). Reusing the key returns the original job.</summary>
public async Task<CaptureJob> SubmitJobAsync(CaptureRequest request, string? idempotencyKey = null, CancellationToken ct = default)
{
using var response = await PostAsync("api/jobs", request, idempotencyKey, ct);
return (await response.Content.ReadFromJsonAsync<CaptureJob>(Json, ct))!;
}
public async Task<CaptureJob> GetJobAsync(string id, CancellationToken ct = default)
{
using var message = new HttpRequestMessage(HttpMethod.Get, $"api/jobs/{Uri.EscapeDataString(id)}");
message.Headers.Add("x-api-key", _apiKey);
using var response = await http.SendAsync(message, ct);
if (!response.IsSuccessStatusCode) throw await ScreenshotlyException.FromResponseAsync(response, ct);
return (await response.Content.ReadFromJsonAsync<CaptureJob>(Json, ct))!;
}
public async Task<CaptureJob> WaitForJobAsync(string id, TimeSpan timeout, CancellationToken ct = default)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(timeout);
var pause = TimeSpan.FromSeconds(2);
while (true)
{
var job = await GetJobAsync(id, cts.Token);
if (job.Status is "SUCCEEDED" or "FAILED" or "CANCELED") return job;
await Task.Delay(pause, cts.Token);
pause = TimeSpan.FromSeconds(Math.Min(pause.TotalSeconds * 2, 15));
}
}
/// <summary>
/// Downloads a signed resultUrl. The key is only attached to API calls,
/// so it is never sent to the storage host behind the signed URL.
/// </summary>
public async Task DownloadAsync(string resultUrl, string path, CancellationToken ct = default)
{
using var response = await http.GetAsync(new Uri(resultUrl), HttpCompletionOption.ResponseHeadersRead, ct);
response.EnsureSuccessStatusCode();
await using var file = File.Create(path);
await response.Content.CopyToAsync(file, ct);
}
private async Task<HttpResponseMessage> PostAsync(string path, CaptureRequest request, string? idempotencyKey, CancellationToken ct)
{
var body = JsonSerializer.Serialize(request, Json);
using var message = new HttpRequestMessage(HttpMethod.Post, path)
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
message.Headers.Add("x-api-key", _apiKey);
if (idempotencyKey is not null) message.Headers.Add("Idempotency-Key", idempotencyKey);
var response = await http.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, ct);
if (response.IsSuccessStatusCode) return response;
using (response) throw await ScreenshotlyException.FromResponseAsync(response, ct);
}
}
The API key is added to each API request rather than to DefaultRequestHeaders. That way DownloadAsync can reuse the same HttpClient for a signed resultUrl without sending your key to the storage host behind it.
Registration and resilience
using System.Net;
using Microsoft.Extensions.Http.Resilience;
using Microsoft.Extensions.Options;
using Polly;
using Polly.Timeout;
namespace Screenshotly;
public static class ScreenshotlyServiceCollectionExtensions
{
// Longer Retry-After values mean the monthly quota is used up: fail fast.
private static readonly TimeSpan MaxRetryAfter = TimeSpan.FromSeconds(60);
public static IServiceCollection AddScreenshotly(this IServiceCollection services, IConfiguration config)
{
services.AddOptions<ScreenshotlyOptions>()
.Bind(config.GetSection("Screenshotly"))
.Validate(o => !string.IsNullOrWhiteSpace(o.ApiKey), "Screenshotly:ApiKey is required")
.ValidateOnStart();
services.AddHttpClient<ScreenshotlyClient>((sp, client) =>
{
client.BaseAddress = new Uri(sp.GetRequiredService<IOptions<ScreenshotlyOptions>>().Value.BaseUrl);
client.Timeout = Timeout.InfiniteTimeSpan; // the pipeline below owns timeouts
})
.AddResilienceHandler("screenshotly", pipeline =>
{
pipeline.AddTimeout(TimeSpan.FromMinutes(3)); // whole operation, retries included
pipeline.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
Delay = TimeSpan.FromSeconds(1),
ShouldRetryAfterHeader = true, // wait exactly as long as a 429 asks
ShouldHandle = args => ValueTask.FromResult(ShouldRetry(args.Outcome)),
});
// Per attempt. Navigation alone may take up to 30 s, plus any
// delay or waitForSelector you request.
pipeline.AddTimeout(TimeSpan.FromSeconds(60));
});
return services;
}
private static bool ShouldRetry(Outcome<HttpResponseMessage> outcome)
{
if (outcome.Exception is HttpRequestException or TimeoutRejectedException) return true;
var response = outcome.Result;
if (response is null) return false;
return response.StatusCode switch
{
HttpStatusCode.TooManyRequests =>
(response.Headers.RetryAfter?.Delta ?? TimeSpan.Zero) <= MaxRetryAfter,
HttpStatusCode.InternalServerError or HttpStatusCode.BadGateway
or HttpStatusCode.ServiceUnavailable or HttpStatusCode.GatewayTimeout => true,
_ => false, // 400, 401, 403, 413: fix the request, key or plan instead
};
}
}
Why the pipeline looks like this:
- Timeouts. A capture can take tens of seconds: page navigation alone may take up to 30 seconds, plus any
delayorwaitForSelector. The inner timeout gives each attempt 60 seconds, and the outer one bounds the whole call including retries.HttpClient.Timeoutis disabled so it doesn't cut the pipeline short. For pages that need longer, use the jobs API. - 429s. A per-minute throttle returns a short
Retry-After, andShouldRetryAfterHeaderwaits exactly that long. When the monthly quota is used up,Retry-Aftercan be days.ShouldRetryrefuses to wait on those, so the caller gets aScreenshotlyExceptionstraight away. - Errors that need a fix aren't retried.
400,401,403and413won't succeed on a second attempt. - Duplicates. A timed-out attempt may still have completed on the server and used a capture. Where that matters, use a job with an
Idempotency-Key.
Configuration:
{
"Screenshotly": {
"BaseUrl": "https://screenshotly.app",
"WebhookUrl": "https://your-app.example.com/webhooks/screenshotly"
}
}
Supply Screenshotly:ApiKey and Screenshotly:WebhookSecret from user secrets in development (dotnet user-secrets set "Screenshotly:ApiKey" "...") and from environment variables (Screenshotly__ApiKey) or a vault in production. ValidateOnStart makes a missing key fail at startup rather than on the first capture.
Using it
public sealed class ThumbnailService(ScreenshotlyClient screenshotly)
{
public async Task RunAsync(CancellationToken ct)
{
// Full-page desktop capture streamed to disk
await screenshotly.CaptureToFileAsync(new CaptureRequest
{
Url = "https://example.com",
Device = "desktop",
FullPage = true,
WaitForNetworkIdle = true,
BlockAds = true,
}, "home.png", ct);
// Exact viewport at 2x density, as WebP
byte[] hero = await screenshotly.CaptureAsync(new CaptureRequest
{
Url = "https://example.com/pricing",
Width = 1440,
Height = 900,
DeviceScaleFactor = 2,
Format = "webp",
Quality = 80,
}, ct);
// Growth plan and above: phone frame, overlays removed
byte[] marketing = await screenshotly.CaptureAsync(new CaptureRequest
{
Url = "https://example.com",
Mockup = "iphone-14",
AiRemoval = new AiRemovalOptions(true, new[] { "cookie-banner", "newsletter" }),
}, ct);
}
}
Options and plan requirements
| Option | Plan | Notes |
|---|---|---|
Format: png, jpeg, webp |
All | Quality 0–100 |
Device, Width/Height, FullPage, DeviceScaleFactor |
All | Width 320–3840, height 240–3840, scale 1–3 |
Delay, WaitForSelector, WaitForNetworkIdle, Selector, BlockAds, DarkMode |
All | Delay up to 10,000 ms |
Format: pdf, html |
Basic+ | PDF is A4 with 1 cm margins; other paper sizes aren't available |
Storage, Webhook, headers, cookies, cache, stealth |
Basic+ | |
Mockup, AiRemoval, HideSelectors, javascript, scroll, geolocation |
Growth+ | Mockups: browser-light, browser-dark, browser-minimal, iphone-14, ipad-pro, macbook-pro |
webm format, proxyRegion |
Scale | WebM videoDuration 1–15 s; regions us, eu, apac |
A gated option on a lower plan returns 403 with "error": "Plan upgrade required". ScreenshotlyException.MinimumPlan tells you which plan it needs.
Error reference
| Status | Meaning | What to do |
|---|---|---|
400 |
Invalid JSON, a schema violation, or a URL that resolves to a private address | Fix the request; details or message says what failed |
401 |
Missing or invalid API key | Check the key; don't retry |
403 |
Plan upgrade required (see minimumPlan), or the account email is not verified yet |
Change the request or plan, or verify the email; don't retry |
413 |
Request body larger than 64 KB | Trim large javascript, headers or cookies values |
429 |
Per-minute limit (short Retry-After) or monthly quota used up (long Retry-After) |
Retry only the short case |
500 |
The capture failed, for example because the target page errored | Retry with backoff; failed captures are not billed |
503 |
The capture proxy is unavailable | Retry with backoff |
Per-minute limits are 5 requests on Free, 40 on Basic, 80 on Growth and 200 on Scale.
Queue captures and receive signed webhooks
On Basic and higher, let Screenshotly run the capture as a durable job and call you back. The endpoint below returns 202 immediately. The Idempotency-Key makes a retried call return the original job, and the webhook header comes back with the delivery so you can match it to your record.
using System.Text.Json;
using Screenshotly;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScreenshotly(builder.Configuration);
builder.Services.AddSingleton(new WebhookVerifier(
builder.Configuration["Screenshotly:WebhookSecret"] ?? throw new InvalidOperationException("Screenshotly:WebhookSecret is required")));
builder.Services.AddSingleton<CaptureQueue>();
builder.Services.AddHostedService<CaptureWorker>();
var app = builder.Build();
// Queue a durable capture with Screenshotly and return straight away.
app.MapPost("/reports/{reportId}/snapshot", async (string reportId, ScreenshotlyClient screenshotly, IConfiguration config, CancellationToken ct) =>
{
var job = await screenshotly.SubmitJobAsync(new CaptureRequest
{
Url = $"https://app.example.com/reports/{reportId}",
Format = "pdf", // Basic+; fixed A4 with 1 cm margins
WaitForNetworkIdle = true,
Webhook = new WebhookOptions(
Url: config["Screenshotly:WebhookUrl"]!,
Secret: config["Screenshotly:WebhookSecret"],
Headers: new Dictionary<string, string> { ["X-Report-Id"] = reportId }),
}, idempotencyKey: $"report-{reportId}", ct);
return Results.Accepted(value: new { jobId = job.Id, job.Status });
});
app.MapPost("/webhooks/screenshotly", async (HttpRequest request, WebhookVerifier verifier, ILogger<Program> log) =>
{
// Verify the raw bytes; re-serialized JSON would not match the signature.
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer);
var body = buffer.ToArray();
if (!verifier.IsValid(body, request.Headers["X-Screenshotly-Signature"]))
return Results.Unauthorized();
using var doc = JsonDocument.Parse(body);
var evt = doc.RootElement.GetProperty("event").GetString();
var data = doc.RootElement.GetProperty("data");
var reportId = request.Headers["X-Report-Id"].ToString();
if (evt == "screenshot.completed")
log.LogInformation("Report {ReportId} ready: {Size} bytes", reportId, data.GetProperty("size").GetInt64());
else if (evt == "screenshot.failed")
log.LogWarning("Report {ReportId} failed: {Error}", reportId, data.GetProperty("error").GetString());
// Respond quickly; download data.storageUrl (signed, short-lived) in the background.
return Results.NoContent();
});
app.Run();
public partial class Program { }
WebhookVerifier checks X-Screenshotly-Signature: sha256=<hex>, which is an HMAC-SHA256 of the raw body keyed with your webhook.secret. It uses a constant-time comparison:
using System.Security.Cryptography;
using System.Text;
namespace Screenshotly;
/// <summary>Checks X-Screenshotly-Signature: sha256=<hex HMAC-SHA256 of the raw body>.</summary>
public sealed class WebhookVerifier(string secret)
{
private readonly byte[] _key = Encoding.UTF8.GetBytes(secret);
public bool IsValid(ReadOnlySpan<byte> rawBody, string? signatureHeader)
{
const string prefix = "sha256=";
if (signatureHeader is null || !signatureHeader.StartsWith(prefix, StringComparison.Ordinal)) return false;
byte[] received;
try { received = Convert.FromHexString(signatureHeader.AsSpan(prefix.Length)); }
catch (FormatException) { return false; }
byte[] expected = HMACSHA256.HashData(_key, rawBody);
return CryptographicOperations.FixedTimeEquals(expected, received);
}
}
A completed delivery looks like this. Failed jobs send "event": "screenshot.failed" with data.error.
{
"event": "screenshot.completed",
"timestamp": "2026-11-13T08:00:00.000Z",
"data": {
"url": "https://app.example.com/reports/42",
"format": "pdf",
"size": 1234,
"storageUrl": "https://screenshotly.app/api/assets/...",
"duration": 4200
}
}
Screenshotly makes up to five delivery attempts if your endpoint doesn't answer with a 2xx, and it does not follow redirects. Keep the handler idempotent and fast. Download storageUrl, which is signed and short-lived, after you respond.
Polling instead of webhooks
var job = await screenshotly.SubmitJobAsync(
new CaptureRequest { Url = "https://example.com/annual-report", Format = "pdf" },
idempotencyKey: "annual-report-2026", ct);
var done = await screenshotly.WaitForJobAsync(job.Id, TimeSpan.FromMinutes(5), ct);
if (done.Status == "SUCCEEDED")
{
await screenshotly.DownloadAsync(done.ResultUrl!, "annual-report.pdf", ct);
}
Job status is QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED. Screenshotly makes up to three attempts at a job before it reports FAILED. If a resultUrl has expired, read the job again for a fresh one.
On Growth and Scale, POST /api/jobs/batch queues up to 20 captures in one call with a body of {"captures": [ ... ]}, where each item is a normal capture request. See the async jobs reference.
Background processing with Channels
For synchronous captures you start yourself (on any plan), push work onto a bounded channel and let a BackgroundService drain it with limited parallelism:
using System.Threading.Channels;
namespace Screenshotly;
public sealed record CaptureWork(CaptureRequest Request, string OutputPath);
public sealed class CaptureQueue
{
private readonly Channel<CaptureWork> _channel = Channel.CreateBounded<CaptureWork>(
new BoundedChannelOptions(500) { FullMode = BoundedChannelFullMode.Wait });
public ValueTask EnqueueAsync(CaptureWork work, CancellationToken ct = default) => _channel.Writer.WriteAsync(work, ct);
public IAsyncEnumerable<CaptureWork> ReadAllAsync(CancellationToken ct) => _channel.Reader.ReadAllAsync(ct);
}
public sealed class CaptureWorker(CaptureQueue queue, IServiceScopeFactory scopes, ILogger<CaptureWorker> log)
: BackgroundService
{
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Parallel.ForEachAsync(
queue.ReadAllAsync(stoppingToken),
new ParallelOptions { MaxDegreeOfParallelism = 4, CancellationToken = stoppingToken },
async (work, ct) =>
{
// Typed clients are transient: resolve one per unit of work rather
// than holding a single HttpClient for the lifetime of the worker.
using var scope = scopes.CreateScope();
var client = scope.ServiceProvider.GetRequiredService<ScreenshotlyClient>();
try
{
await client.CaptureToFileAsync(work.Request, work.OutputPath, ct);
log.LogInformation("Captured {Url} to {Path}", work.Request.Url, work.OutputPath);
}
catch (ScreenshotlyException ex)
{
log.LogWarning("Capture of {Url} failed: {Status} {Error}", work.Request.Url, (int)ex.Status, ex.Error);
}
});
}
The program above registers it with AddSingleton<CaptureQueue>() and AddHostedService<CaptureWorker>(). A caller enqueues with await queue.EnqueueAsync(new CaptureWork(request, path)). BoundedChannelFullMode.Wait makes producers wait when 500 items are queued instead of growing memory without limit.
Two limits to keep in mind. An in-memory channel loses whatever is queued when the process restarts, so use /api/jobs or a durable queue for work you can't lose. And MaxDegreeOfParallelism should match your plan's per-minute limit: on Free, one or two is enough.
Batch captures
For a one-off list, Parallel.ForEachAsync gives bounded concurrency without a queue:
var urls = new[] { "https://example.com", "https://example.com/about", "https://example.com/pricing" };
await Parallel.ForEachAsync(
urls.Select((url, index) => (url, index)),
new ParallelOptions { MaxDegreeOfParallelism = 2, CancellationToken = ct },
async (item, token) =>
{
try
{
await screenshotly.CaptureToFileAsync(new CaptureRequest { Url = item.url }, $"page-{item.index}.png", token);
}
catch (ScreenshotlyException ex)
{
Console.WriteLine($"{item.url}: {(int)ex.Status} {ex.Error}");
}
});
Caching
- API-side (Basic+): set
cache: trueand optionallycacheTtl(60–86,400 seconds, default 3,600) so Screenshotly reuses a recent result. Add both as nullable properties onCaptureRequest. - In-process: if you cache bytes in
IMemoryCache, build the key from the full serialized request, for exampleJsonSerializer.Serialize(request, ScreenshotlyClient.Json)hashed withSHA256.HashData, so different options never share an entry. If you set a size on each entry, the cache must have aSizeLimit.
Testing
A stub HttpMessageHandler lets you assert the exact request without a mocking library:
using System.Net;
using System.Text;
using Microsoft.Extensions.Options;
using Screenshotly;
using Xunit;
public sealed class StubHandler(Func<HttpRequestMessage, HttpResponseMessage> respond) : HttpMessageHandler
{
public List<(HttpRequestMessage Request, string? Body)> Calls { get; } = new();
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
var body = request.Content is null ? null : await request.Content.ReadAsStringAsync(ct);
Calls.Add((request, body));
return respond(request);
}
}
public class ScreenshotlyClientTests
{
private static ScreenshotlyClient CreateClient(StubHandler handler) =>
new(new HttpClient(handler) { BaseAddress = new Uri("https://screenshotly.app") },
Options.Create(new ScreenshotlyOptions { ApiKey = "test-key" }));
[Fact]
public async Task Capture_SendsKeyAndOmitsNullFields()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(new byte[] { 0x89, 0x50, 0x4E, 0x47 }),
});
var bytes = await CreateClient(handler).CaptureAsync(new CaptureRequest { Url = "https://example.com", Width = 1280, Height = 800 });
Assert.Equal(0x89, bytes[0]);
var (request, body) = Assert.Single(handler.Calls);
Assert.Equal("https://screenshotly.app/api/screenshot", request.RequestUri!.ToString());
Assert.Equal("test-key", request.Headers.GetValues("x-api-key").Single());
Assert.Equal("""{"url":"https://example.com","format":"png","width":1280,"height":800}""", body);
}
[Fact]
public async Task PlanError_MapsToTypedException()
{
var handler = new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.Forbidden)
{
Content = new StringContent("""{"error":"Plan upgrade required","message":"PDF output requires the basic plan or higher","minimumPlan":"basic"}""", Encoding.UTF8, "application/json"),
});
var ex = await Assert.ThrowsAsync<ScreenshotlyException>(() =>
CreateClient(handler).CaptureAsync(new CaptureRequest { Url = "https://example.com", Format = "pdf" }));
Assert.Equal(HttpStatusCode.Forbidden, ex.Status);
Assert.Equal("basic", ex.MinimumPlan);
}
[Fact]
public void WebhookVerifier_AcceptsKnownSignature()
{
var verifier = new WebhookVerifier("whsec_test");
var body = Encoding.UTF8.GetBytes("""{"event":"screenshot.completed"}""");
Assert.True(verifier.IsValid(body, "sha256=595255b9b9f3ded02941a21a8ca07a418e784abc584ce3d5dbe59e646ca25cf7"));
Assert.False(verifier.IsValid(body, "sha256=595255b9b9f3ded02941a21a8ca07a418e784abc584ce3d5dbe59e646ca25cf8"));
Assert.False(verifier.IsValid(body, "sha256=zz"));
Assert.False(verifier.IsValid(body, null));
}
}
The expected signature is the HMAC-SHA256 of that body with the secret whsec_test. Reproduce it with printf '%s' '{"event":"screenshot.completed"}' | openssl dgst -sha256 -hmac whsec_test. To test the webhook endpoint end to end, use WebApplicationFactory<Program> from Microsoft.AspNetCore.Mvc.Testing. The public partial class Program { } line in Program.cs exists for that.
Production checklist
- The key comes from configuration or a vault, never from source, and it never reaches the browser.
- Typed client via
AddHttpClient, with the resilience pipeline owning timeouts (60 s per attempt). - Unset options are omitted (
WhenWritingNull), and names are camelCase. 429is retried only for shortRetry-Aftervalues;400,401,403and413are never retried.- Large captures are streamed with
ResponseHeadersReadandCopyToAsync. - Slow pages, PDFs and batches go through
/api/jobswith anIdempotency-Key. - Webhook handlers verify the raw body with
CryptographicOperations.FixedTimeEquals, respond quickly and are idempotent. - Worker parallelism is sized to the plan's per-minute limit.
Conclusion
On .NET 8 you need HttpClient, System.Text.Json and one resilience package. Use the console quick start to check your key, the typed client for services, and jobs with signed webhooks once captures leave the request path.
Ready to add screenshots to your .NET app?
Get your free API key →. The Free plan includes 100 captures to test with.
See also:
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
Why use IHttpClientFactory instead of new HttpClient()?
Creating and disposing HttpClient instances per request can exhaust sockets, and a single static instance can miss DNS changes. IHttpClientFactory (AddHttpClient in DI) pools and rotates handlers for you and is where resilience handlers attach. A short console tool can use one long-lived HttpClient instead.
Why does the API return 'Invalid request data'?
The schema is strict: unknown keys and explicit nulls are rejected. Serialize with JsonSerializerDefaults.Web (camelCase) and DefaultIgnoreCondition = WhenWritingNull so unset options are omitted. Width and height are top-level fields; there is no nested viewport object.
Where should screenshot capture run in ASP.NET Core?
Not inline in a request for anything slow, because a capture can take tens of seconds. On Basic and higher, queue it with POST /api/jobs and receive a signed webhook when it finishes. Otherwise use a BackgroundService that reads from a bounded Channel, and remember an in-memory channel loses queued work on restart.
How do I add retries cleanly?
Use Microsoft.Extensions.Http.Resilience (built on Polly v8) and attach a pipeline to the typed client with AddResilienceHandler. Retry 429 only when Retry-After is short, retry 5xx with exponential backoff and jitter, and never retry 400, 401, 403 or 413.
What happens if I use a feature my plan doesn't include?
The API returns 403 'Plan upgrade required' with a minimumPlan field. PDF and HTML output, webhooks, stored results and custom headers or cookies need Basic. Mockups, AI element removal, custom JavaScript and hideSelectors need Growth. WebM video and regional proxies need Scale.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.