Tutorial

Screenshot API with ASP.NET Core — HttpClient, Background Services & Blazor

Integrate SnapAPI screenshot capture into ASP.NET Core with HttpClient, IHostedService background workers, Blazor components, and Azure deployment.

Screenshot API in ASP.NET Core with HttpClient

ASP.NET Core applications call the SnapAPI screenshot endpoint using the IHttpClientFactory pattern, which manages HttpClient instance lifetimes correctly and avoids socket exhaustion from improper HttpClient disposal. Register a named HttpClient for SnapAPI in Program.cs using builder.Services.AddHttpClient("snapapi", client => { client.BaseAddress = new Uri("https://snapapi.pics"); }). Inject the IHttpClientFactory interface into your controller or service and call CreateClient("snapapi") to get a properly managed HttpClient instance. Construct the request URL with QueryString parameters for the access key and target URL, call GetAsync to send the request, and read the response content as a byte array with ReadAsByteArrayAsync for binary PNG responses or as a string with ReadAsStringAsync followed by JsonSerializer.Deserialize for JSON responses. The typed HttpClient variant provides a cleaner interface for services that exclusively call the SnapAPI endpoint.

ASP.NET Core minimal API endpoints that proxy screenshot requests to SnapAPI implement the route handler as an async lambda that reads the url query parameter, validates it, calls the SnapAPI HttpClient, and returns a Results.File response with the PNG bytes and the image/png content type. Minimal API route handlers are more concise than controller-based alternatives for simple proxy endpoints with no complex business logic. Add rate limiting middleware to the minimal API using the RateLimiter middleware with a fixed window or sliding window policy keyed to the client's IP address or user identity to prevent individual clients from exhausting the SnapAPI monthly quota through the proxy endpoint. ASP.NET Core's built-in rate limiting middleware, introduced in .NET 7, handles this without requiring a third-party middleware package.

Screenshot API ASP.NET Core Background Services

ASP.NET Core IHostedService background services process screenshot generation jobs from a queue without blocking the main request pipeline. Define a ScreenshotWorkerService class that implements BackgroundService and overrides the ExecuteAsync method with a loop that dequeues screenshot jobs from a Channel or a database-backed queue, calls the SnapAPI endpoint using a typed HttpClient, stores the result, and updates the job status. Register the background service in Program.cs with builder.Services.AddHostedService to start it automatically when the application starts. The background service runs concurrently with the HTTP request pipeline, processing screenshot jobs asynchronously while the web application continues handling user requests normally. For ASP.NET Core applications deployed on Azure App Service, configure Always On to prevent the application from being shut down when idle, which would terminate in-progress background screenshot processing.

ASP.NET Core applications can use Azure Queue Storage or Azure Service Bus as the backing queue for screenshot jobs in cloud deployments, providing durable job storage that persists screenshot requests across application restarts and scales horizontally across multiple application instances. When a web request triggers a screenshot, enqueue a message containing the target URL and job metadata to Azure Queue Storage using the Azure.Storage.Queues SDK. The background worker service dequeues messages, calls SnapAPI for each job, and stores results in Azure Blob Storage. Multiple application instances can process jobs concurrently by each running an instance of the background service, with Azure Queue Storage's message lease mechanism preventing duplicate processing of the same job by multiple workers.

Screenshot API with Blazor Server Components

Blazor Server components that display screenshot thumbnails call the SnapAPI endpoint from C# server-side code using the injected HttpClient, then update the component state to render the screenshot. Define a Blazor component with an ImageUrl parameter or a TargetUrl parameter, a private string screenshotSrc field for the image source, and a bool loading field for the loading state. In the OnParametersSetAsync lifecycle method, set loading to true, call the SnapAPI screenshot proxy endpoint using the injected HttpClient, encode the resulting byte array as a base64 data URL string, assign it to screenshotSrc, and set loading to false. The Blazor rendering engine updates the DOM automatically when the state changes, displaying the loading indicator while the screenshot generates and the image when it completes. For Blazor components displayed in lists, use a CancellationToken tied to the component lifecycle to cancel in-flight requests when components are removed from the DOM.

Screenshot API .NET SDK Integration

The SnapAPI .NET SDK wraps the HttpClient integration pattern in a clean, testable interface with async methods, strongly typed request and response objects, and built-in retry logic for transient errors. Add the NuGet package SnapAPI.Net to your project, configure the client with your API key from the IConfiguration system, and inject the SnapAPIClient into services and controllers through the standard dependency injection container. The SDK's ScreenshotAsync method accepts a ScreenshotOptions record with properties for all supported parameters and returns a ScreenshotResult record with the image bytes, HTTP status code of the captured page, and page metadata. The strongly typed interface eliminates the query string construction and response parsing boilerplate from every call site and provides IntelliSense documentation for all parameters and response fields in Visual Studio and Rider.

Screenshot API ASP.NET Core with Polly Resilience

ASP.NET Core applications use the Polly resilience library to add retry, circuit breaker, and timeout policies to SnapAPI HTTP calls, making screenshot generation robust against transient network failures. Configure Polly policies when registering the SnapAPI named HttpClient in Program.cs using the AddPolicyHandler extension from the Microsoft.Extensions.Http.Polly package. Define a retry policy with exponential backoff that retries on HttpRequestException and on 429 and 500 status code responses. Add a circuit breaker policy that opens after five consecutive failures and resets after 30 seconds, preventing cascading failures when SnapAPI experiences downtime. Add a timeout policy set to 30 seconds per request to prevent screenshot calls from hanging indefinitely if the SnapAPI endpoint is unresponsive. The layered Polly policies provide defense in depth against the full range of failure modes in production HTTP calls without custom retry or timeout logic in service code.

Screenshot API ASP.NET Core Health Checks

ASP.NET Core health check endpoints can include a custom SnapAPI connectivity check that verifies the screenshot API is reachable and the configured API key is valid. Define a SnapAPIHealthCheck class implementing IHealthCheck that calls the SnapAPI endpoint with a known test URL, checks for a successful response, and returns HealthCheckResult.Healthy or HealthCheckResult.Unhealthy based on the response. Register the health check in Program.cs with builder.Services.AddHealthChecks().AddCheck("snapapi", new SnapAPIHealthCheck()). The health check endpoint at /health reports SnapAPI connectivity alongside other application dependencies, giving operations teams a single endpoint to monitor application health including external API dependencies. Container orchestration platforms like Kubernetes and Azure Container Apps can use the health check endpoint as a readiness probe to route traffic away from application instances that have lost connectivity to SnapAPI.

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

ASP.NET Core applications with SignalR can push screenshot generation results to connected browser clients in real time without polling. When a user requests a screenshot from a Blazor or JavaScript client, the server dispatches the screenshot generation task to a background queue and immediately returns a job ID to the client. The client subscribes to a SignalR hub channel keyed to the job ID. When the background service completes screenshot generation and stores the result, it sends a SignalR message to the job ID channel with the screenshot URL. The JavaScript SignalR client receives the message and updates the UI with the loaded screenshot. The SignalR push pattern eliminates polling latency — screenshots appear in the UI as soon as they are ready, typically within one to three seconds — and reduces server load by eliminating repeated HTTP polling requests from waiting clients.

Screenshot API ASP.NET Core Middleware for Request Logging

A custom ASP.NET Core middleware component inserted before the screenshot proxy endpoint logs all screenshot requests with structured metadata for observability and debugging. The middleware reads the target URL from the query string before passing the request downstream, records the start timestamp, yields to the next middleware in the pipeline which calls SnapAPI and returns the response, then logs the target URL domain, HTTP status code, response time in milliseconds, and response size in bytes to the structured logging provider. The structured log entries are automatically ingested by Azure Application Insights, Seq, or any other structured logging backend configured for the ASP.NET Core application. Querying the screenshot log entries provides visibility into which target URLs cause the most errors, which have the highest latency, and which consume the most API bandwidth — actionable information for optimizing screenshot generation performance and cost.