Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Microsoft Playwright for .NET to render the target URL in Chromium, then call Page.ScreenshotAsync. The method can return PNG, JPEG, or WebP bytes directly from an ASP.NET endpoint, save a file, capture the full scrollable document, or limit the image to an element or clipped rectangle.

The complete Minimal API example below accepts a URL, validates its scheme, waits for the document, captures a full-page PNG, and returns image/png. For production, reuse the browser process, isolate each request in its own context or page, set timeouts, and protect any endpoint that accepts arbitrary URLs.

Build the ASP.NET endpoint

Prerequisites

  • An ASP.NET Core application targeting a supported .NET version.
  • The Microsoft.Playwright NuGet package.
  • A Playwright-managed Chromium installation on the machine or container that runs the API.
  • Network access from that server to the pages you intend to capture.

Add the package with:

dotnet add package Microsoft.Playwright

After building the project, install the browser binary using the Playwright installation script generated in your output directory. The exact path includes your target framework and build configuration, so use the script produced by your project rather than copying a fixed path from another application.

Complete Minimal API example

This endpoint uses a required url query parameter and returns a full-page PNG as bytes. It allows only HTTP and HTTPS schemes; production services should also block private, loopback, link-local, and metadata-service addresses to prevent server-side request forgery.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
using Microsoft.Playwright;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/screenshot", async (HttpRequest request) =>
{
    var rawUrl = request.Query["url"].ToString();
    if (!Uri.TryCreate(rawUrl, UriKind.Absolute, out var target) ||
        (target.Scheme != Uri.UriSchemeHttp && target.Scheme != Uri.UriSchemeHttps))
    {
        return Results.BadRequest("Provide an absolute http or https URL.");
    }

    using var playwright = await Playwright.CreateAsync();
    await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
    {
        Headless = true
    });

    var page = await browser.NewPageAsync(new BrowserNewPageOptions
    {
        ViewportSize = new ViewportSize { Width = 1440, Height = 900 }
    });

    await page.GotoAsync(target.ToString(), new PageGotoOptions
    {
        WaitUntil = WaitUntilState.DOMContentLoaded,
        Timeout = 30_000
    });

    var bytes = await page.ScreenshotAsync(new PageScreenshotOptions
    {
        Type = ScreenshotType.Png,
        FullPage = true,
        Timeout = 30_000
    });

    return Results.File(bytes, "image/png");
});

app.Run();

ScreenshotAsync returns a byte[] when no Path is supplied, so Results.File can send it without creating a temporary file. The endpoint signature can be adapted to an MVC controller or Razor application; the rendering calls remain the same.

Install and launch Playwright reliably

Playwright controls a real browser engine, which is why page JavaScript, CSS layout, fonts, and responsive behavior are rendered before the image is taken. Your deployment must contain a browser binary compatible with the Playwright package version. In CI or a container, install browsers during the image-build step and verify that the process user can execute them and write its temporary profile directory.

Launching Chromium for every request, as the short example does, is easy to understand but adds startup latency and process churn. For sustained traffic, create one long-lived browser per application instance and create a new browser context or page for each request. Close the page and context in a finally block, cap concurrent captures with a semaphore, and close the shared browser during application shutdown. A context per request prevents cookies, local storage, cache, and permissions from leaking between callers.

Choose the capture scope

Goal Playwright call or option What you receive
Visible viewport page.ScreenshotAsync with default options The current viewport at its configured width and height.
Entire document FullPage = true A tall image covering the full scrollable page, including content below the fold.
One element page.Locator(".header").ScreenshotAsync(...) The element’s rendered bounding box, including its visible contents.
Specific rectangle Clip = new Clip { X, Y, Width, Height } Only the coordinates you define, measured in CSS pixels.

Viewport screenshot

Omit FullPage when the requirement is a browser-like viewport rather than a complete document. Set the viewport on the context or page before navigation so responsive breakpoints are evaluated at the intended width.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Full-page screenshot

Set FullPage = true to capture the full scrollable page as if it could fit on a very tall screen. Long pages can create large images, consume more memory, and take longer to transmit. Use this mode only when the complete document is needed.

Element screenshot

Capture a component with a locator:

var card = page.Locator("article.product-card");
await card.WaitForAsync(new LocatorWaitForOptions { State = WaitForSelectorState.Visible });
var bytes = await card.ScreenshotAsync(new LocatorScreenshotOptions
{
    Type = ScreenshotType.Webp,
    Quality = 85
});

Use a stable CSS selector or a test identifier rather than a fragile positional selector. Waiting for visibility prevents a screenshot of an element that has not yet been inserted or is still hidden.

Clipped region

var bytes = await page.ScreenshotAsync(new PageScreenshotOptions
{
    Type = ScreenshotType.Png,
    Clip = new Clip
    {
        X = 0,
        Y = 0,
        Width = 1200,
        Height = 800
    }
});

A clip is useful for a chart, hero area, or fixed-size design review. Confirm that the coordinates match the viewport and that the requested rectangle is within the rendered page.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Control format, scale, and output

PNG, JPEG, and WebP

The Page API documents PNG, JPEG, and WebP screenshot types. PNG is lossless and has no quality setting. JPEG and WebP accept a quality value, which trades file size against detail:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var jpeg = await page.ScreenshotAsync(new PageScreenshotOptions
{
    Type = ScreenshotType.Jpeg,
    Quality = 82,
    FullPage = true
});

var webp = await page.ScreenshotAsync(new PageScreenshotOptions
{
    Type = ScreenshotType.Webp,
    Quality = 82,
    FullPage = true
});

Return the matching MIME type: image/png, image/jpeg, or image/webp. Do not send a JPEG quality value with PNG.

Save to a file instead of returning bytes

Specify Path when a later job needs a durable artifact:

await page.ScreenshotAsync(new PageScreenshotOptions
{
    Path = "artifacts/home.webp",
    Type = ScreenshotType.Webp,
    Quality = 85
});

The format is inferred from the extension when a path is used. Ensure the directory exists and that the worker identity has write permission. For an HTTP response, omitting Path avoids a disk round trip.

CSS pixels and device pixels

The Scale option can target CSS pixels or device pixels. CSS-pixel output keeps dimensions predictable across device scale factors; device-pixel output is useful when you need a retina-density asset and can accept a larger file. Set the browser context’s viewport and device scale factor deliberately rather than relying on host defaults.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Other rendering controls

The screenshot options also expose timeout, caret visibility, animation handling, masking, background omission, and an inline stylesheet. Disable or mask unstable regions when you need repeatable visual comparisons. An inline stylesheet can hide timestamps, rotating promotions, or other content that would otherwise make identical pages differ between runs.

Wait for the page you actually want

DOMContentLoaded means the initial document has been parsed; it does not guarantee that data fetched by JavaScript or lazy images is ready. Choose a wait strategy based on the target site:

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Wait for a selector

await page.GotoAsync(url, new PageGotoOptions
{
    WaitUntil = WaitUntilState.DOMContentLoaded,
    Timeout = 30_000
});
await page.WaitForSelectorAsync("main article", new PageWaitForSelectorOptions
{
    State = WaitForSelectorState.Visible,
    Timeout = 15_000
});

Wait for a known delay

await page.WaitForTimeoutAsync(1500);

A fixed delay is simple but brittle: it may be too short on a slow run and waste time on a fast one. Prefer a selector or application-specific readiness signal where possible.

Wait for network activity to settle

WaitUntilState.NetworkIdle can help on pages that finish their requests cleanly, but analytics, long polling, advertisements, and WebSockets may keep a page busy indefinitely. Use a bounded timeout and fall back to a selector-based wait when a site never becomes idle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Lazy-loaded images and infinite scroll

Full-page capture does not guarantee that every lazy image has loaded. Scroll through the document or wait for the image elements you need, then capture. Infinite-scroll pages require an application-specific stopping rule; otherwise a full-page operation may continue growing or time out.

Authenticated pages, headers, and browser state

Create a browser context with the required viewport, locale, timezone, or user agent. For authenticated content, set cookies or perform a login inside that context before navigating to the final URL. Keep credentials out of query strings and logs. Close the context after the capture so tokens cannot be reused by another request.

When an endpoint accepts arbitrary destinations, validate the URL before launching navigation, resolve DNS safely, and deny private address ranges, loopback, link-local addresses, cloud metadata endpoints, and unexpected ports. Restrict outbound traffic at the network layer as a second control. If users can supply custom headers or scripts, allow-list them and never execute untrusted server-side code outside the browser sandbox.

Production design for speed and reliability

Reuse the browser, isolate the page

Keep a shared Chromium process or managed browser pool, but create a fresh context and page for each capture. This avoids the startup cost of a new process while preserving isolation. Dispose pages even when navigation or screenshot operations throw.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Bound work and concurrency

Set separate navigation and screenshot timeouts. Limit concurrent pages according to available CPU and memory; full-page images and high device scales can consume substantially more memory than viewport PNGs. Return a clear 4xx response for invalid input and a 5xx or problem-details response for internal capture failures rather than returning an empty image.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Cache deliberately

If the same URL is requested repeatedly, cache the resulting bytes with a key that includes viewport, format, quality, authentication context, and relevant rendering options. Set an explicit expiration because a screenshot is a time-dependent representation of a page. Do not share cached authenticated images between users.

Deployment and observability

Verify browser dependencies in the exact operating-system image used in production. Log the target host, elapsed navigation time, elapsed screenshot time, output dimensions, byte count, and a sanitized failure category. Avoid logging cookies, Authorization headers, or full URLs when they contain secrets. Add health checks that exercise browser launch without navigating to an external site.

Troubleshooting common failures

Symptom Likely cause Fix
Browser executable not found The Playwright browser was not installed in the deployment image, or the package and browser versions do not match. Run the generated Playwright browser-install script during deployment and confirm the runtime user can execute it.
Navigation timeout The site is slow, blocked, waiting on an endless request, or unreachable from the server. Check outbound connectivity, use a bounded timeout, wait for a specific selector instead of network idle, and return a useful timeout error.
Blank or partially rendered image Capture occurred before client-side rendering, fonts, or lazy images completed. Wait for a visible application selector, required images, or an explicit readiness flag; increase the timeout only after identifying what is missing.
Element locator fails The selector is wrong, the element is inside a frame, or it is created after navigation. Inspect the selector, wait for visibility, and target the correct frame before calling Locator.
Full-page image is unexpectedly huge The document is extremely tall, has an infinite-scroll loop, or uses a large device scale factor. Use a viewport, element, or clip capture; constrain scrolling; and select CSS-pixel scale.
Only a white page is captured The page requires a login, blocks the server’s IP, fails JavaScript, or navigated to an error document. Inspect the final URL and response, establish authentication in the context, and test the target from the deployment network.
Requests leak across users A page or context was reused with cookies or local storage still present. Create a new context per request and close it in a finally block; never use a shared page for unrelated users.

When to return bytes and when to store files

Return bytes directly for an image endpoint, proxy, or API consumed immediately by a browser. Set a cache policy appropriate to the page’s sensitivity and include the exact content type. Store a file when another worker will process it, when you need an audit artifact, or when object storage handles delivery more efficiently than the API process. In either case, enforce maximum dimensions and output sizes to protect memory and bandwidth.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a hosted website screenshot API and MCP server. It accepts one GET request and returns a PNG, JPEG, WebP, or PDF, so your ASP.NET code does not have to install or maintain Chromium. Its capture pipeline accepts cookie and consent banners like a visitor, then removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Here is the cURL call (the ScreenshotNeo documentation lists the full parameter set):

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Call it from C#

using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(90) };
var response = await client.GetAsync(
    "https://api.screenshotneo.com/v1/shot?access_key=YOUR_API_KEY&url=https%3A%2F%2Fstripe.com");
response.EnsureSuccessStatusCode();
var imageBytes = await response.Content.ReadAsByteArrayAsync();
return Results.File(imageBytes, response.Content.Headers.ContentType?.MediaType ?? "image/webp");

Python and Node.js equivalents

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());

Options useful from an ASP.NET service

  • Full-page capture with lazy images loaded, or one element selected by CSS.
  • Dark mode, 12 device presets, arbitrary viewport sizes, and retina scale.
  • PDF output with paper size, margins, landscape mode, and page ranges.
  • HTML/CSS-to-image, custom CSS and JavaScript, pre-capture clicks, hidden selectors, and waits for a selector, delay, or network idle.
  • Blocking for ads, trackers, requests, or resource types.
  • Custom headers, cookies, user agent, Authorization, timezone, geolocation, and transparent backgrounds.
  • Image resizing, a cache with a caller-selected TTL, signed links for public <img> tags, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification.
  • Parameter names used by other screenshot APIs also work, which reduces migration changes.

The MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients. Every feature is available on every plan:

Plan Included shots Price
Free 1,000 per month $0, no card
Starter 3,000 $5
Growth 15,000 $15
Pro 60,000 $39
Scale 250,000 $99
Business 1,000,000 $249

Yearly billing gives two months free. Failed loads and other non-clean outcomes are not billed, while successful clean captures are. Create a free ScreenshotNeo account to try 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Does Playwright capture what a normal browser renders?

Yes. It drives a browser engine, so JavaScript and CSS are evaluated before the screenshot rather than treating the URL as a static HTTP document.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Can I capture an element instead of the whole page?

Yes. Use a locator’s ScreenshotAsync method for the element, or use the page-level Clip option for a coordinate rectangle.

Should I launch Chromium for every request?

Only for a small example or very low traffic. A shared browser with isolated per-request contexts is normally more efficient and safer under load.

Which format should an API return?

Use PNG for lossless UI or text, JPEG for photographic content when smaller files matter, and WebP when clients support it and you want a modern size-quality trade-off.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can an ASP.NET endpoint capture a page that requires login?

Yes. Create an isolated Playwright context, establish the session by setting cookies or completing the login flow, then navigate to the protected URL before calling ScreenshotAsync.

How do I stop an endpoint from becoming an SSRF proxy?

Allow-list HTTP and HTTPS, reject private and metadata-network addresses after DNS resolution, restrict ports and outbound egress, and avoid exposing arbitrary header or script execution to untrusted callers.

What is the simplest hosted alternative to managing Playwright browsers?

ScreenshotNeo provides a GET screenshot API and MCP tools; its free plan includes 1,000 shots per month without a card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.