Skip to content

Guide · C# (.NET)

Generate Open Graph images in C# (.NET)

Every post needs a share image, and drawing them by hand does not scale. This C# (.NET) program sends the post’s title, category and author to a template and gets back a PNG on the CDN, ready for the og:image meta tag.

Free plan with 100 units a month, no credit card

What you need

  • An API key. Create one in the app under API keys and export it as FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start.
  • C# (.NET). You need the .NET 8 SDK; the program uses System.Net.Http.Json and System.Text.Json, which ship with it.
  • The template. og-image from the Open Graph example: Tailwind classes, compiled at render time, no stylesheet to keep.
  • The data. The example’s data.json next to the program: category, title, publication date, reading time and the author with an avatar URL.
InstallShell
dotnet new console -o render && cd render   # then replace Program.cs

The program

The program reads data.json, asks for png, marks the output public, waits for the result when the API answers 202, and saves the image; download_url is its address on the CDN.

Program.csC#
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

var data = JsonDocument.Parse(File.ReadAllText("data.json")).RootElement;
var body = new
{
    template = "og-image",
    data,
    output = "png",
    access = "public",
};

using var http = new HttpClient();

// one call to the API: the key goes on each request, never on the client, so no other address sees it
async Task<HttpResponseMessage> Send(HttpMethod method, string url, object? content = null)
{
    using var request = new HttpRequestMessage(method, url) { Content = content is null ? null : JsonContent.Create(content) };
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("FORMFEED_API_KEY"));
    return await http.SendAsync(request);
}

var response = await Send(HttpMethod.Post, "https://api-eu.formfeed.dev/v1/renders", body);
var render = await response.Content.ReadFromJsonAsync<JsonElement>();

// not done within 60 seconds: the answer is 202 and the render goes on in the background;
// its result answers the same way until the render has finished
while ((int)response.StatusCode == 202)
{
    await Task.Delay(2000);
    response = await Send(HttpMethod.Get, $"https://api-eu.formfeed.dev/v1/renders/{render.GetProperty("id")}/result");
    render = await response.Content.ReadFromJsonAsync<JsonElement>();
}

// every error is a problem document (RFC 9457) with a title and a detail
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine($"{render.GetProperty("title")}: {(render.TryGetProperty("detail", out var detail) ? detail : "")}");
    return 1;
}

await File.WriteAllBytesAsync("og-image.png", await http.GetByteArrayAsync(render.GetProperty("download_url").GetString()));
Console.WriteLine($"{render.GetProperty("id")} {render.GetProperty("download_url")}");
return 0;

Run it

It prints the render’s id and the download URL, and og-image.png lies next to the program. Open it: 1200 × 630 pixels, the title truncated to fit, the avatar round.

Shell
export FORMFEED_API_KEY=ff_test_...
dotnet run

What is particular about C# (.NET)

  • Anonymous objects. The API’s field names are snake_case and are written as they are (webhook_url = …), so no naming policy has to be configured.
  • Data without classes. JsonDocument.Parse(…).RootElement embeds the sample data untouched; in your application this is your own record or DTO.
  • Key on the request, not the client. The Authorization header is set on each request to the API, never on the HttpClient: the download goes to a signed CDN URL and must not carry your API key.

What the two options do

  • output: "png". Names the format of the image. jpg and webp work as well; the pixel size, the scale factor and the format of a request without output come from the template’s image settings.
  • access: "public". Gives a CDN URL without a signature, which is what a meta tag needs: a scraper has no API key. The address works for as long as the file is kept, which the retention of your plan decides, so serve the saved image from your own site when a page is shared for longer. Use it only for images that may be public.

Render once, not on every request

An identical request with a live key within 24 hours is answered from the deduplication cache at zero units, so a second deploy on the same day costs nothing (test keys cost nothing anyway and are never deduplicated). After that the image is rendered again: store the image or its URL with the post and render when the post changes, never inside the page handler, because a social scraper will not wait for a render. See deduplication.

One template, many sizes

Open Graph wants 1200 × 630, and other networks want other frames. Put the size in the request’s settings.image instead of the template, and the same markup renders every format you need.

When the API says no

  • One shape for every error. Errors are problem documents (RFC 9457) with type, title, status, detail, a stable code and the request_id to quote to support; the type URL leads to a page about that error. The list is in the error reference.
  • The usual ones. 401 unauthorized for a missing or revoked key, 404 template_not_found for a wrong template name, 422 template_runtime_error when the template fails on the data, 429 rate_limited above the plan’s requests per second, 402 quota_exceeded when the Free plan’s units are used up (a paid plan bills extra units up to its hard cap).
  • Retry safely. Send an Idempotency-Key header with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.

The job around this program

This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Open Graph image API.

More C# (.NET) guides

FAQ

Does the image count as a render?
Yes, one unit per image, like a one-page PDF. Test renders are free. See pricing.
Can I use my own fonts?
Yes: link a web font in the template’s head, which the renderer fetches and caches, or, from the Starter plan on, upload font files in the app under Fonts and name the family in your CSS. See fonts.
Why is my text cut off?
The frame is fixed, so a long headline has to give. The example truncates with truncate: 70; a smaller font size or a two-line clamp in CSS works as well.

Open Graph image in other languages

Start rendering today

The free plan includes 100 units a month and free test renders. Change plans when you need more.