# Add e-signatures and clickwrap with .NET

> Build a signup clickwrap in ASP.NET Core minimal APIs with HttpClient, System.Text.Json and session state, calling the Esign Comply REST API. No NuGet package.

Source: https://esigncomply.com/docs/quickstart/dotnet

Last updated November 26, 2026

To add e-signatures and clickwrap with .NET, call the REST API from ASP.NET Core with `HttpClient` and the secret key: there is no NuGet package. One minimal API route creates the session, session state holds the pinned versions, another route confirms the record, and the browser SDK attaches to your checkbox. Esign Comply seals each acceptance as an independent record.

Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my .NET app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/dotnet.md (the steps and the tested code for .NET)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

.NET facts
- There is no Esign Comply package for .NET. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key, using an HttpClient from IHttpClientFactory.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is the configuration value ESIGNCOMPLY_API_KEY: an environment variable, or a user secret in the Development environment. Never put it in appsettings.json or in launchSettings.json. Never print the key.
- HttpClient.BaseAddress must end with a slash and the paths must not start with one, or "/v1" is dropped from every address.
- The API's JSON is snake_case. Read and write it with JsonNamingPolicy.SnakeCaseLower: with the web defaults a typed read leaves client_token null and throws nothing. Send the documents to the browser as the API sent them.
- SendAsync does not throw on 4xx and 5xx, and GetFromJsonAsync does. Check the status code before you read the record.
- Keep the signer ID and the pinned version IDs in ASP.NET Core session state (AddDistributedMemoryCache, AddSession, UseSession), or in the store the project already has.
- Return the document HTML with Results.Content and the content type text/html, unmodified. A string returned from a handler is sent as text/plain.
- Minimal APIs do not validate an antiforgery token on a POST that carries JSON. If the project validates one on its API routes, send the token with both POST requests.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Route for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in session state, and return only clientToken, apiUrl and documents.
4. Route for GET /legal/{slug}: render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Route for POST /api/signup/confirm: call GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in session state. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:5000/signup --callback http://localhost:5000/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

The rest of this page is the same integration by hand, in eight steps.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- The .NET SDK, version 8 or later: the code uses `JsonNamingPolicy.SnakeCaseLower`, which .NET has had since version 8. This page was run on .NET 10, the current LTS release, with SDK 10.0.404 and ASP.NET Core 10.0.15.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

No package needed. The server SDK exists for Node.js only, so an ASP.NET Core app calls the REST API directly with `HttpClient` and `System.Text.Json`, which .NET ships. The page loads the browser SDK from a script tag. To follow along in a new app:

```bash
dotnet new web -o esigncomply-quickstart
cd esigncomply-quickstart
mkdir wwwroot
```

`dotnet new web` creates the empty ASP.NET Core project: `Program.cs`, the project file, `appsettings.json` and `Properties/launchSettings.json`. The template picks a port for each project and writes it into the launch settings: in the test run it was 5054. Change it to 5000, so the addresses on this page are yours too. This is the file of the test project, with the `https` profile and `launchBrowser` taken out:

```json file="Properties/launchSettings.json"
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
```

## Step 2. Set the key

Put the key in `.env` in the project folder. .NET does not read this file: you load it into the shell that starts the app, and ASP.NET Core's configuration reads the variables from the environment.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "plan_name": "Free",
  "test_events": {
    "used_this_month": 0,
    "quota_per_month": 500
  }
}
```

A `401` means the key is wrong or revoked: see [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/auth.md).

ASP.NET Core has a place of its own for a development secret, the Secret Manager: `dotnet user-secrets init`, then `dotnet user-secrets set ESIGNCOMPLY_API_KEY` with your key. The code on this page reads it with no change, because `builder.Configuration` reads user secrets and environment variables alike. Three things were seen when this was tried with a test setting:

- A user secret was read under `dotnet run`, which starts the app in the `Development` environment. It was not read by `dotnet run --no-launch-profile`, which started the app in `Production`.
- An environment variable of the same name won over the user secret.
- A value under `environmentVariables` in `launchSettings.json` won over the variable in the shell. Never put the key in that file: it sits in the project folder.

The secret was stored as plain JSON in `~/.microsoft/usersecrets/`, in a file only its owner can read. Microsoft's documentation says the Secret Manager does not encrypt what it stores and is for development only.

## Step 3. Register a document version

Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs `curl` and `jq`.

```bash
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"

# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
  | jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
  | jq -r .id; sleep 1

# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
  -d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)

printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
```

It prints the two version IDs, then three lines with your own IDs:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.env`, then load the file into your shell again. The pauses keep the script under the Free plan's 2 requests per second. Keep the names `Terms of Service` and `Privacy Notice`: the notice on your page names each document by its registered name, and rule [CR-02](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`Program.cs` is the whole server: the signup page, the two document pages, the route that creates the session, and the route that confirms the record. The `EsignComply` class is the entire client: one HTTPS call with the secret key that returns the status and the JSON answer, sent again only when the API answers `429`. `AddHttpClient` registers it with `IHttpClientFactory`, and each route asks for it as a parameter. This replaces the `Program.cs` that `dotnet new web` wrote:

```csharp file="Program.cs"
// Program.cs
using System.Net.Http.Headers;
using System.Text.Encodings.Web;
using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

// Configuration reads environment variables, and user secrets in the Development environment.
var config = builder.Configuration;
var live = config["ESIGNCOMPLY_LIVE"] == "true"; // set it in production only
string[] sealedStatuses = ["recorded", "timestamped", "anchored"];
var documents = new Dictionary<string, string?>
{
    ["terms"] = config["ESIGNCOMPLY_TERMS_ID"],
    ["privacy"] = config["ESIGNCOMPLY_PRIVACY_ID"],
};

// The signer. In your app this is the signed-in user, or the account you are about to create.
var signer = new Signer("user_7c1d", "dana@example.org", "Dana Whitfield", "consumer", "US", "US-CA");

// There is no .NET package: these are plain HTTPS calls with the secret key, through IHttpClientFactory.
builder.Services.AddHttpClient<EsignComply>(client =>
{
    // The trailing slash matters: without it HttpClient drops "/v1" from every address.
    client.BaseAddress = new Uri((config["ESIGNCOMPLY_API_URL"] ?? "https://esigncomply.com/v1").TrimEnd('/') + "/");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", config["ESIGNCOMPLY_API_KEY"]);
    client.Timeout = TimeSpan.FromSeconds(10);
});

// Server-owned state: ASP.NET Core's session. The data stays in the memory of this process,
// and the browser holds only the session ID, in a cookie that Data Protection encrypts.
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = live ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
    options.Cookie.IsEssential = true;
});

var app = builder.Build();
app.UseSession();

// The page is wwwroot/signup.html. A path that is not rooted is looked up in the web root.
app.MapGet("/signup", () => Results.File("signup.html", "text/html; charset=utf-8"));

// The document pages: each one renders a registered version, unmodified.
app.MapGet("/legal/{slug}", async (string slug, string? v, EsignComply esc) =>
{
    if (documents.GetValueOrDefault(slug) is not { } documentId) return Results.NotFound();
    var version = Uri.EscapeDataString(string.IsNullOrEmpty(v) ? "current" : v);
    var (status, content) = await esc.Call<DocumentContent>(HttpMethod.Get, $"documents/{documentId}/versions/{version}/content");
    if (status != 200 || content?.Html is null) return Results.NotFound();

    // The version ID goes into an attribute, so it is encoded. Results.Content writes the document HTML as it is.
    var id = HtmlEncoder.Default.Encode(content.VersionId ?? "");
    return Results.Content($"<!doctype html><meta charset=\"utf-8\"><article data-esc-document=\"{id}\">{content.Html}</article>", "text/html; charset=utf-8");
});

// Step 4: create the session with the secret key. The browser gets the client token only.
app.MapPost("/api/ceremony", async (HttpContext context, EsignComply esc) =>
{
    // The page that runs the ceremony: the origin the browser reports, or the scheme and host ASP.NET Core saw.
    var origin = context.Request.Headers.Origin.FirstOrDefault() ?? $"{context.Request.Scheme}://{context.Request.Host}";
    var (status, created) = await esc.Call<Session>(HttpMethod.Post, "sessions", new
    {
        Profile = config["ESIGNCOMPLY_PROFILE_ID"],
        Signer = signer,
        Documents = new[]
        {
            new { Document = documents["terms"], Version = "current" },
            new { Document = documents["privacy"], Version = "current" },
        },
        Context = new { Url = $"{origin}/signup", Locale = "en-US", Purpose = "account_signup" },
    }, idempotencyKey: $"signup-{signer.ExternalId}-{Guid.NewGuid():N}");
    if (status != 201 || created is null) return Results.Json(new { error = created?.Error?.Code ?? "unknown" }, statusCode: 502);

    var versionIds = created.Documents.EnumerateArray().Select(d => d.GetProperty("version_id").GetString()).Order();
    context.Session.SetString("signer_id", signer.ExternalId);
    context.Session.SetString("version_ids", string.Join(",", versionIds));
    // The documents go to the browser as the API sent them: a JsonElement is written unchanged.
    return Results.Json(new { clientToken = created.ClientToken, apiUrl = created.ApiUrl, documents = created.Documents });
});

// Step 6: confirm the record with the secret key before the account exists.
app.MapPost("/api/signup/confirm", async (ConfirmRequest body, HttpContext context, EsignComply esc) =>
{
    var (status, record) = await esc.Call<SignatureRecord>(HttpMethod.Get, $"records/{Uri.EscapeDataString(body.RecordId ?? "missing")}");

    var confirmed = status == 200 && record?.Documents is not null
        && sealedStatuses.Contains(record.Status)
        && record.Livemode == live
        && context.Session.GetString("signer_id") is { } signerId && record.Signer?.ExternalId == signerId
        && context.Session.GetString("version_ids") == string.Join(",", record.Documents.Select(d => d.VersionId).Order());

    if (!confirmed)
    {
        app.Logger.LogInformation("refused");
        return Results.Json(new { confirmed = false }, statusCode: 409);
    }
    app.Logger.LogInformation("confirmed {Id} ({Status})", record!.Id, record.Status);
    // Only now create the account, and store record.Id and the record's receipt with it.
    return Results.Json(new { confirmed = true, recordId = record.Id });
});

app.Run();

/// <summary>One call to the Esign Comply API. Returns the HTTP status and the JSON answer.</summary>
class EsignComply(HttpClient http)
{
    // The API's fields are snake_case. The web defaults look for clientToken, find nothing and leave null.
    static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };

    public async Task<(int Status, T? Body)> Call<T>(HttpMethod method, string path, object? body = null, string? idempotencyKey = null)
    {
        for (var attempt = 1; ; attempt++)
        {
            // A request message is sent once, so each attempt builds its own.
            using var request = new HttpRequestMessage(method, path); // no leading slash: the path is relative to BaseAddress
            if (body is not null) request.Content = JsonContent.Create(body, options: Json);
            if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
            using var response = await http.SendAsync(request);
            // Rate limited: wait for the seconds in Retry-After, 1 at least and 5 at most, and send it again, twice at most.
            if ((int)response.StatusCode == 429 && attempt < 3)
            {
                var seconds = response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 1;
                await Task.Delay(TimeSpan.FromSeconds(Math.Clamp(seconds, 1, 5)));
                continue;
            }
            // SendAsync does not throw on 4xx and 5xx: the status is here, and the error envelope is the body.
            return ((int)response.StatusCode, await response.Content.ReadFromJsonAsync<T>(Json));
        }
    }
}

record Signer(string ExternalId, string Email, string Name, string Class, string Country, string Region);
record ApiError(string? Code);
record Session(string? ClientToken, string? ApiUrl, JsonElement Documents, ApiError? Error);
record PinnedDocument(string? DocumentId, string? VersionId);
record SignatureRecord(string? Id, string? Status, bool? Livemode, Signer? Signer, PinnedDocument[]? Documents);
record DocumentContent(string? VersionId, string? Html);
record ConfirmRequest(string? RecordId);
```

The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

Four things here are specific to .NET, and each one was seen in the test run.

The base address ends with a slash, and the paths start without one. `HttpClient` drops everything after the last slash of `BaseAddress` when it combines the two, and the API URL ends in `/v1`. Of the four combinations tried, only this one reached `/v1/usage`. The other three were sent to `/usage`, without `/v1`, and were answered `404` with an HTML page. With the slash taken off in `Program.cs`, the session route asked for `/sessions` and answered `500`, with `JsonException: '<' is an invalid start of a value` in the log.

The JSON options carry `JsonNamingPolicy.SnakeCaseLower`. The API's fields are `client_token`, `api_url` and `version_id`, and the web defaults of `System.Text.Json` look for `clientToken`. With the web defaults the answer of the API was read into a record whose `ClientToken` and `ApiUrl` were `null`, and nothing was thrown. They also wrote the signer's `ExternalId` as `externalId`. `Results.Json` uses the web defaults too: typed documents came out with `documentId` and `versionId`, which the page does not read. So `Session.Documents` is a `JsonElement`, and the route hands it to the browser as the API sent it.

`SendAsync` returns a refusal as an answer. A made-up record ID came back as status `404` with the error envelope in the body, and the envelope read into `SignatureRecord` with every property `null`. `GetFromJsonAsync` threw instead: `HttpRequestException: Response status code does not indicate success: 404 (Not Found).`

When the API answers `429`, `Call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice, with a new `HttpRequestMessage` each time. The wait is an awaited `Task.Delay`, so it holds no thread: in the test, page requests sent while two confirmations waited were answered in under 0.01 seconds.

The pinned versions are in ASP.NET Core's session state, because it is the framework's own and keeps them on the server. The browser got a cookie named `.AspNetCore.Session`, 182 characters long, `HttpOnly` and `SameSite=Lax`. It holds the session ID, encrypted by Data Protection, and the signer ID and the version IDs stay in the memory of the process. After a restart, the same cookie with a real record ID was answered `409`: the API had answered `200`, and the versions to compare with were gone.

`context.url` is built from the `Origin` header the browser sends with the `POST`. A request without one falls back to `Request.Scheme` and `Request.Host`, and all three come from the client. A request with `Origin: https://evil.example` was refused by the API with `domain_mismatch`, and the route answered `502`. So was a request with no `Origin` and `Host: evil.example`: the `appsettings.json` of the template has `"AllowedHosts": "*"`. With `AllowedHosts` set to `localhost`, ASP.NET Core answered a request with that `Host` header `400` itself.

Start the app from the shell that loaded `.env`:

```bash
dotnet run
```

```text
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
```

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as `wwwroot/signup.html`:

```html file="wwwroot/signup.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Create account</title>
    <style>
      body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
      a { color: #0b57d0; text-decoration: underline; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="assent">
        <!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
        <label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
        <p>
          By checking the box and clicking Create account, you agree to the
          <a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
          <a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
        </p>
        <button id="create-account" type="submit" disabled>Create account</button>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      const { clientToken, apiUrl, documents } = await response.json();

      const ceremony = await EsignComply.attach({ clientToken, apiUrl });
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });

      // Point each link at the exact version this session pinned, then report it.
      const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
      for (const [i, link] of links.entries()) {
        link.search = "?v=" + documents[i].version_id;
        await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, links, checkbox, button
        checkbox: agree,
        submit,
      });
      agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.

      document.querySelector("#signup").addEventListener("submit", async (event) => {
        event.preventDefault();
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your server confirms the record before anything is granted.
          const confirmed = await fetch("/api/signup/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ recordId: result.recordId }),
          });
          message.textContent = confirmed.ok
            ? `Account created. Record ${result.recordId}`
            : "We could not confirm whether your acceptance was recorded. Please wait while we check.";
        } catch (error) {
          message.textContent = error.message;
        }
      });
    </script>
  </body>
</html>
```

`Results.File` looks up a path that is not rooted in the web root, which is `wwwroot`, so the `/signup` route serves this file. The app does not call `UseStaticFiles`, and `/signup.html` was answered `404`.

Open [http://localhost:5000/signup](http://localhost:5000/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_VoiKD3D1bh2tNVoQxb1Z
```

The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it. In a test without `disabled` and with the session request held back, a box ticked in that time stayed ticked, and the SDK reported a finding for [CR-01](https://esigncomply.com/docs/conformance.md#cr-01) at Block level: the control had already been used when the SDK started watching it. With `disabled`, the same early click did nothing. One page load sent one `POST /api/ceremony`.

Each link opens a document page on your own server that renders the registered version. `Results.Content` with the content type `text/html` writes the string as it is, and the route encodes only the version ID, which goes into an attribute. In a test with `HtmlEncoder.Default.Encode()` around the document, the page showed the tags as text and the SDK reported a finding for [CR-08](https://esigncomply.com/docs/conformance.md#cr-08) at Block level: the page behind the link did not match the registered version. A handler that returns the string itself has another problem: ASP.NET Core sent it as `text/plain`.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. `POST /api/signup/confirm` in `Program.cs` reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one in session state; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app logs one line for each confirmation:

```text
info: esigncomply-quickstart[0]
      confirmed rec_VoiKD3D1bh2tNVoQxb1Z (recorded)
```

`IHttpClientFactory` logs every call to the API around it, with the address and the status. The key was not in those lines.

A record ID that was made up is refused with status `409`. So is a real record ID sent without the session cookie, or with a cookie the app cannot decrypt:

```bash
curl -s -X POST http://localhost:5000/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

That request carried no token of any kind, and ASP.NET Core let it through to the handler: minimal APIs do not validate an antiforgery token on a `POST` that carries JSON. In a test with `AddAntiforgery`, `UseAntiforgery` and `RequireAntiforgeryToken` on the route, a request with no token and the `Origin` of another site still ran the handler, with `IAntiforgeryValidationFeature.IsValid` set to `false`. Microsoft's documentation says the antiforgery middleware does not short-circuit the pipeline. Only a call to `IAntiforgery.ValidateRequestAsync` in the handler refused the request. What refuses a forged confirmation here is the check itself.

A `POST` with no JSON never reaches the handler. ASP.NET Core answered `400` to an empty body and `415` to a body with no JSON content type.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:5000/signup --callback http://localhost:5000/api/signup/confirm
```

The report for this page's code, shortened:

```text
Violations that must be refused
  REFUSED   Submit with the checkbox untouched      No record was made.
  REFUSED   Completion from another origin          The API answered 403 domain_mismatch.
  REFUSED   Programmatic click                      No record was made.
  REFUSED   Forged success posted to your callback  http://localhost:5000/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_VabuXvwBaMPFPbQEQTTf  session ses_nFNJ4t2uAMU4R1cshrnF, 5 events
  768x1024   record rec_BE06PbEd1wLcQnA7hBjQ  session ses_PBmotqCPcZuLadq10gry, 5 events
  1440x900   record rec_DscBkZ15EVnsye5Z1bHr  session ses_3sqeTiL6eZ5nLXkAXJuS, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

The app logged a `confirmed` line for each of the three records.

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then switch the server over:

- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in the environment of the production process only. From then on the confirm route refuses every test record there, and the session cookie is marked `Secure`.
- Publish with `dotnet publish -c Release`, and start the published app from the folder it was published to. `launchSettings.json` is not published. In the test the published app ran in the `Production` environment, read no user secret, took its address from `--urls`, and recorded the signature shown in step 5. Started from another folder it answered `500` on `/signup`, with `Could not find file: signup.html` in the log: the content root is the folder the process starts in.
- Session state lives in the memory of one process, and its cookie is encrypted with Data Protection keys. In a container the app warned that its keys `may not be persisted outside of the container`, and a cookie from a container that had been removed was answered `409`, with `was not found in the key ring` in the log. With more than one instance, or on a host that replaces containers, keep the pinned versions in your database. Store the record ID and the receipt beside the user either way.
- Session state is dropped when it has been idle for the `IdleTimeout`, and Microsoft's documentation gives the default as 20 minutes. With the timeout set to 3 seconds in a test, a value was gone 5 seconds later. A visitor who signs after that is answered `409`.
- Behind a proxy that terminates TLS, `Request.Scheme` is `http` until forwarded headers are processed. In the test a request with `X-Forwarded-Proto: https` was seen as `http`, and as `https` once `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` was set. The session route does not depend on it, because the browser sends `Origin`.

In live mode `context.url` must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.

## Troubleshooting

- **`missing_api_key` from `/api/ceremony`.** The configuration has no `ESIGNCOMPLY_API_KEY`. The app starts without it: in the test it answered `502` with this code. Either the shell that ran `dotnet run` did not load `.env`, or the key is a user secret and the app is not in the `Development` environment, as with a published app. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`500` from every route that calls the API, and `JsonException: '<' is an invalid start of a value` in the log.** The request went to an address without `/v1`, and the answer was an HTML page. Give `BaseAddress` a slash at the end and start the paths without one, as `Program.cs` does. The log line from `IHttpClientFactory` shows the address that was asked for.
- **`429` when the confirm route reads the record.** `Call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered `200`, two of them a second later than the others. The log lines from `IHttpClientFactory` showed why: two reads got `429` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the route answers `409` for a real record, the cause is session state that is gone: a restart, or 20 minutes without a request.

## Questions about the .NET quickstart

### Is there a NuGet package for Esign Comply?

No. The server SDK exists for Node.js only. An ASP.NET Core app calls the REST API directly, and this quickstart does it with `HttpClient` and `System.Text.Json`, so the project file lists no package reference.

### Which .NET version does the quickstart need?

.NET 8 or later. The code uses `JsonNamingPolicy.SnakeCaseLower`, which Microsoft's documentation lists as available in .NET 8 and later versions. The quickstart was run on .NET 10, the current long-term support release, with SDK 10.0.404 and ASP.NET Core 10.0.15.

### Does dotnet run read the .env file?

No. In the test, with `.env` in the project folder and the key missing from the environment, `dotnet run` started the app and the session route answered `502` with `missing_api_key`. Load the file into the shell first, or keep the key in the Secret Manager while you develop.

### Why does the published app run in the Production environment?

Because nothing tells it otherwise. `launchSettings.json` sets `ASPNETCORE_ENVIRONMENT` to `Development` for `dotnet run`, and the file is not published. In the test the published app logged the hosting environment as Production, and so did `dotnet run --no-launch-profile`. User secrets were not read there.

### Why does the conformance check need Node.js?

The checker is the `esigncomply` command line tool, which is a Node.js package. It drives a headless browser against your page, whatever language serves it. Install it in a folder of its own, as step 7 shows, and your .NET project stays free of Node.js files.

### Does the .NET quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for .NET](https://esigncomply.com/dotnet): what the integration gives you on this stack, with the things to watch for.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this server makes.
- [Add e-signatures and clickwrap with Node.js](https://esigncomply.com/docs/quickstart/nodejs.md): the same flow with the server SDK.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
