Screenshot API .NET C# Guide 2026

Integrate SnapAPI into ASP.NET Core with HttpClient, IHostedService background processing, Azure Blob Storage, and Polly resilience. Full C# code examples.

Get Free API Key

Calling SnapAPI from .NET with HttpClient

ASP.NET Core applications call the SnapAPI REST endpoint using the HttpClient registered via IHttpClientFactory, which manages HttpClient lifetime and connection pooling correctly, avoiding the socket exhaustion issues that occur when creating new HttpClient instances per request. Register a named or typed SnapAPI HttpClient in Program.cs using builder.Services.AddHttpClient, configure the base address to https://api.snapapi.pics, and add a DelegatingHandler that sets the Authorization header with the Bearer API key. Inject the IHttpClientFactory into the SnapApiService and create a client using factory.CreateClient("snapapi") for each request. Use QueryHelpers.AddQueryString from Microsoft.AspNetCore.WebUtilities to build the screenshot endpoint URL with query parameters in a type-safe way rather than string concatenation. Read the response content as a byte array using HttpContent.ReadAsByteArrayAsync for screenshot responses that return binary image data.

// Program.cs
builder.Services.AddHttpClient("snapapi", client => {
    client.BaseAddress = new Uri("https://api.snapapi.pics");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer",
            builder.Configuration["SnapApi:Key"]);
    client.Timeout = TimeSpan.FromSeconds(60);
});
builder.Services.AddScoped();

// SnapApiService.cs
public class SnapApiService(IHttpClientFactory factory) {
    public async Task ScreenshotAsync(
        string url, bool fullPage = false,
        string format = "png",
        CancellationToken ct = default)
    {
        var client = factory.CreateClient("snapapi");
        var query = QueryHelpers.AddQueryString("/screenshot", new Dictionary {
            ["url"] = url,
            ["format"] = format,
            ["full_page"] = fullPage.ToString().ToLower(),
        });
        var resp = await client.GetAsync(query, ct);
        resp.EnsureSuccessStatusCode();
        return await resp.Content.ReadAsByteArrayAsync(ct);
    }
}

Background Screenshot Processing with IHostedService

ASP.NET Core applications use IHostedService or BackgroundService for asynchronous screenshot generation that runs outside the HTTP request pipeline. Define a ScreenshotWorker class inheriting BackgroundService that reads screenshot requests from a Channel, calls SnapApiService.ScreenshotAsync for each request, uploads the result to Azure Blob Storage, and updates the screenshot record status in the database. Write screenshot requests to the Channel from ASP.NET Core controllers using ChannelWriter.WriteAsync after creating a pending screenshot record, returning 202 Accepted to the client immediately. The BackgroundService processes requests from the Channel concurrently using Task.WhenAll with a configurable parallelism limit enforced by a SemaphoreSlim, preventing more concurrent SnapAPI calls than the configured maximum. Register the ScreenshotWorker in Program.cs with builder.Services.AddHostedService() so ASP.NET Core starts and stops it with the application lifecycle.

Azure Blob Storage for Screenshots in .NET

ASP.NET Core applications store SnapAPI screenshot bytes in Azure Blob Storage using the Azure.Storage.Blobs NuGet package. Register a BlobServiceClient using builder.Services.AddAzureClients with the connection string from configuration, and inject BlobContainerClient into the storage service. After receiving screenshot bytes from SnapApiService, upload them using BlobClient.UploadAsync with a blob name derived from a GUID or a hash of the source URL. Generate SAS URLs for time-limited download access using BlobSasBuilder with the configured expiry duration. Cache SAS URLs in IMemoryCache or IDistributedCache with an expiry shorter than the SAS token validity, regenerating the token before expiry to maintain continuous access. Use Azure CDN in front of the Blob Storage container to serve screenshot images with low latency and high availability for applications that display screenshots in the UI to end users.

Get Started with SnapAPI in .NET

Install the SnapAPI .NET SDK from NuGet with dotnet add package SnapApi, configure snap_api:key in appsettings.json or user secrets, and register the client with builder.Services.AddSnapApi(). Register at snapapi.pics/register for a free API key with two hundred requests per month and no credit card. The SDK provides typed methods for all four SnapAPI endpoints with built-in Polly resilience policies for retry and circuit breaking, compatible with .NET 6, .NET 7, .NET 8, and .NET 9 and the ASP.NET Core dependency injection system.

ASP.NET Core Screenshot API with Polly Resilience

Production ASP.NET Core applications use the Polly resilience library to add retry, circuit breaker, and timeout policies to SnapAPI HTTP calls, ensuring reliable screenshot generation under adverse network conditions. Configure Polly policies on the SnapAPI HttpClient registration in Program.cs using AddPolicyHandler. Define a retry policy with exponential backoff that retries on transient HTTP errors and 429 rate limit responses up to three times, waiting two, four, and eight seconds between retries respectively. Define a circuit breaker policy that opens after five consecutive failures and remains open for thirty seconds, preventing cascading failures when SnapAPI is temporarily unreachable. Define a timeout policy with a thirty-second timeout that applies to each individual attempt rather than the total retry budget. Combine all three policies with Policy.WrapAsync in the correct order: outermost retry, then circuit breaker, then timeout, so the timeout applies to each attempt and the circuit breaker tracks failures across retries. These Polly policies provide production-grade resilience without modifying the SnapApiService code, keeping resilience concerns in the infrastructure configuration layer.

Screenshot API SignalR Real-Time Updates in ASP.NET Core

ASP.NET Core applications use SignalR to push real-time screenshot completion notifications to connected clients without polling. Define a ScreenshotHub inheriting Hub with a method that clients call to subscribe to updates for a specific screenshot ID, joining a SignalR group named after the screenshot ID. In the ScreenshotWorker BackgroundService, after uploading the screenshot to Azure Blob Storage and updating the database record, use IHubContext to send a screenshot-completed message to the group associated with the screenshot ID, including the screenshot URL and status in the message payload. The client-side SignalR connection receives the message and updates the UI to display the completed screenshot without a page reload or polling interval. Use the HubContext via dependency injection in the BackgroundService, injecting IHubContext into the ScreenshotWorker constructor and calling Clients.Group(screenshotId).SendAsync("ScreenshotCompleted", payload) after each screenshot completes. This pattern eliminates polling overhead for real-time screenshot status updates in applications where users initiate screenshots and wait for results in an active browser session.

.NET Screenshot API Production Deployment Checklist

Before deploying a .NET SnapAPI integration to production, verify these criteria. The SnapAPI key is stored in Azure Key Vault or ASP.NET Core user secrets for local development and injected via environment variables in Azure App Service or AKS, never committed to source control. The HttpClient timeout is configured at sixty seconds to accommodate slow rendering of complex pages. The BackgroundService screenshot worker has a maximum concurrency limit enforced by SemaphoreSlim to prevent exceeding SnapAPI rate limits. Failed screenshots are retried with Polly and dead-lettered after exceeding the retry limit with an error status record for operational review. Azure Blob Storage access uses managed identity authentication rather than connection strings with storage account keys for improved security. SignalR or a polling endpoint notifies users of screenshot completion so the frontend does not display an indefinite loading spinner. Screenshot generation failures degrade gracefully by displaying a placeholder image rather than an unhandled exception to end users. Register at snapapi.pics/register for a free API key and start your .NET integration today.

Screenshot API .NET SDK and NuGet Package

The SnapAPI .NET SDK is available on NuGet at nuget.org/packages/SnapApi and installs with dotnet add package SnapApi or via the NuGet Package Manager in Visual Studio. The SDK targets .NET Standard 2.0 for broad framework compatibility and provides async methods for all four SnapAPI endpoints: ScreenshotAsync, ScrapeAsync, ExtractAsync, and PdfAsync. Configure the SDK in ASP.NET Core by calling builder.Services.AddSnapApi(options => options.ApiKey = config["SnapApi:Key"]) in Program.cs, which registers a typed ISnapApiClient singleton backed by IHttpClientFactory with the correct Authorization header, base URL, and timeout settings. Inject ISnapApiClient into controllers and services via constructor injection. The SDK includes built-in retry logic using Polly with three retries and exponential backoff on transient errors, and throws SnapApiException with the HTTP status code and error message for non-retryable errors. Source code is MIT-licensed and available at github.com/Sleywill/snapapi-dotnet. Register at snapapi.pics/register for a free API key providing two hundred requests per month with no credit card to start your .NET screenshot integration today.

Screenshot API C# Error Handling and Logging

Production ASP.NET Core SnapAPI integrations use structured logging with ILogger to record all screenshot requests and outcomes for operational monitoring. Log each screenshot request at the Debug level with the source URL and configuration parameters when the request starts, log successful completions at the Information level with the URL and response byte count, and log failures at the Warning or Error level with the URL, HTTP status code, and exception details. Configure log enrichment with Serilog or NLog to include the screenshot record ID as a structured property in all log entries for that request, enabling log correlation by screenshot ID across the service boundary. Set up log-based alerts in your monitoring system to notify the operations team when the screenshot failure rate exceeds a threshold indicating a systemic issue with the SnapAPI integration rather than isolated individual failures. Use the ILogger category name derived from SnapApiService as the logger name so screenshot-specific log entries can be filtered independently from other application logs in your log aggregation system.