# C# and .NET

Source: https://xmlvalid.com/docs/sdks/dotnet

> Validate XRechnung, ZUGFeRD and other e-invoices from C#, and write an XRechnung from your data, with HttpClient and the REST API: no package to install

There is no NuGet package: the API is plain HTTP and JSON, and .NET's `HttpClient` and `System.Text.Json` are all it takes. The examples are for .NET 8 and newer. Each document is one API validation: 100 a month on Free, 10,000 to 100,000 on [Pro](https://xmlvalid.com/pricing).

## Set up

Create an API key under [Dashboard → API keys](https://xmlvalid.com/dashboard/api) and keep it in the environment or your configuration. One `HttpClient` serves the whole application:

```csharp
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

var http = new HttpClient { BaseAddress = new Uri("https://xmlvalid.com/api/v1/") };
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("XMLVALID_API_KEY"));

// The API answers in snake_case: errors_total, rule_url…
var json = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
};
```

In ASP.NET Core, register it with `IHttpClientFactory` instead:

```csharp
builder.Services.AddHttpClient("xmlvalid", client =>
{
    client.BaseAddress = new Uri("https://xmlvalid.com/api/v1/");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["Xmlvalid:ApiKey"]);
});
```

The answers read into a few records. They hold what most code needs; the [OpenAPI description](https://xmlvalid.com/docs/api/openapi.yaml) has every field, and a client can be generated from it with NSwag or Kiota:

```csharp
public record Validation(string Id, string Status, int Progress, ValidationSchema? Schema,
    Result? Result, string? Error, Links Links);

public record ValidationSchema(string? Catalog, bool? Detected);

public record Result(bool Valid, string Outcome, int ErrorsTotal, int WarningsTotal,
    List<Diagnostic> Errors, List<Diagnostic> Warnings, string? Sha256);

public record Diagnostic(int Line, int Column, string Level, string Type, string Message,
    string? Rule, string? Path, string? RuleUrl, string? HelpUrl);

public record Links(string Self, string? Report, string? Document);
```

## Validating a document

Send the file as the multipart field `document` with the schema's slug. The request waits up to `wait` seconds (60 at most) for the result; a validation that takes longer answers `202` with its status, and you ask for it again until it has finished:

```csharp
async Task<Validation> ValidateAsync(string path, string? schema = null)
{
    using var form = new MultipartFormDataContent();
    await using var file = File.OpenRead(path);
    form.Add(new StreamContent(file), "document", Path.GetFileName(path));
    if (schema is not null) form.Add(new StringContent(schema), "schema");
    form.Add(new StringContent("30"), "wait");

    using var response = await http.PostAsync("validations", form);
    return await FinishAsync(response);
}

async Task<Validation> FinishAsync(HttpResponseMessage response)
{
    if (!response.IsSuccessStatusCode)
        throw new HttpRequestException(await response.Content.ReadAsStringAsync(), null, response.StatusCode);

    var validation = (await response.Content.ReadFromJsonAsync<Validation>(json))!;
    while (validation.Status is "queued" or "running")
    {
        await Task.Delay(TimeSpan.FromSeconds(2));
        validation = (await http.GetFromJsonAsync<Validation>($"validations/{validation.Id}", json))!;
    }
    return validation;
}
```

The file is streamed from disk, not read into memory, so a large export goes as it is. A gzipped document (`.gz`) is unpacked on the server, and a `.zip` is validated document by document, up to 1,000. Without a schema a document is checked for well-formedness only; the [catalog](https://xmlvalid.com/schemas) lists every slug, and a schema of your own that spans several files is saved once under [Dashboard → Schemas](https://xmlvalid.com/dashboard/schemas) and named like `@orders-v3`.

## XRechnung, ZUGFeRD and other e-invoices

An e-invoice profile runs the schema and the official business rules in one call: `xrechnung-3-ubl` or `xrechnung-3-cii` checks EN 16931 and KoSIT's XRechnung rules, with the levels of KoSIT's configuration, `peppol-bis-3-invoice` Peppol BIS Billing, and so on.

```csharp
var validation = await ValidateAsync("RE-2026-0042.xml", "xrechnung-3-ubl");

if (validation.Result!.Valid)
    Console.WriteLine("Passes the XRechnung schema and rules");
else
    foreach (var error in validation.Result.Errors)
        Console.WriteLine($"line {error.Line}: [{error.Rule}] {error.Message}");
// line 41: [BR-DE-15] Das Element "Buyer reference" (BT-10) muss übermittelt werden.
```

A ZUGFeRD or Factur-X PDF goes as it is, without a schema: the XML inside is taken out and checked against the profile it names, and what the PDF breaks (the attachment's name and relationship, the XMP metadata, PDF/A) comes back as findings of type `pdf`:

```csharp
var validation = await ValidateAsync("rechnung-0412.pdf");

var pdfProblems = validation.Result!.Errors.Where(e => e.Type == "pdf");   // PDF-AF, PDF-XMP, PDFA-…
```

For invoices of mixed formats, `auto` picks the profile each one names (its specification identifier BT-24, or the root element for national formats such as FatturaPA or KSeF). Look at `Schema.Detected` before trusting a pass, as a document it doesn't recognise is checked for well-formedness only:

```csharp
var validation = await ValidateAsync(path, "auto");
Console.WriteLine($"{validation.Schema?.Catalog} (detected: {validation.Schema?.Detected})");
```

The country guides name the profile each mandate needs: [Germany](https://xmlvalid.com/e-invoicing/germany), [France](https://xmlvalid.com/e-invoicing/france), [Belgium](https://xmlvalid.com/e-invoicing/belgium), [Poland](https://xmlvalid.com/e-invoicing/poland) and more.

## Writing an XRechnung or ZUGFeRD invoice

`POST /invoices` writes the invoice from JSON and checks it against its profile in the same call: XRechnung (UBL or CII), Peppol BIS, ZUGFeRD / Factur-X, France CTC, NLCIUS, KSeF, FatturaPA, Facturae or e-SLOG. Amounts are worked out in decimal as EN 16931 wants them. The fields are the e-invoice generator's, listed in the [API reference](https://xmlvalid.com/docs/api#invoices); they are camelCase, so this request goes with the default options rather than `json`:

```csharp
var request = new
{
    invoice = new
    {
        profile = "xrechnung",            // or "zugferd", "peppol", "france"…
        number = "RE-2026-0042",
        issueDate = "2026-11-27",
        buyerReference = "04011000-12345-03",
        seller = new
        {
            name = "Muster Software GmbH", street = "Hauptstraße 12", city = "Berlin", postcode = "10115", country = "DE",
            vatId = "DE136695976",
            contact = new { name = "Anna Schmidt", phone = "+49 30 1234567", email = "rechnung@muster-software.de" },
        },
        buyer = new
        {
            name = "Beispiel Handel AG", street = "Marktplatz 3", city = "München", postcode = "80331", country = "DE",
            endpoint = new { scheme = "EM", id = "eingang@beispiel-handel.de" },
        },
        payment = new { iban = "DE02120300000000202051", accountName = "Muster Software GmbH" },
        lines = new[]
        {
            new { name = "Softwarelizenz, Jahresabo", quantity = 1m, unit = "ANN", price = 1200m, rate = 19m },
            new { name = "Fachbuch XML", quantity = 2m, unit = "H87", price = 39.90m, rate = 7m },
        },
    },
    format = "xml",                        // "pdf": a ZUGFeRD PDF/A-3 with the XML inside
    wait = 30,
};

using var response = await http.PostAsJsonAsync("invoices", request);
var written = await FinishAsync(response);

if (written.Result!.Valid)
{
    var document = await http.GetByteArrayAsync($"validations/{written.Id}/document");
    await File.WriteAllBytesAsync("RE-2026-0042.xml", document);
}
```

The written document is kept with the result for 24 hours. An invoice that breaks a rule of its profile is still written, so check the outcome before sending it on; the findings name the rule as in any validation.

## Business rules (Schematron)

A schema says which elements may appear; business rules say whether the content makes sense: totals that add up, required fields, code lists. A catalog profile runs its official rules after the schema check, and each finding names its rule and links to a page on what it checks and how to fix it:

```csharp
foreach (var error in validation.Result!.Errors.Where(e => e.Type == "schematron"))
    Console.WriteLine($"{error.Rule} at {error.Path}: {error.Message}\n  {error.RuleUrl}");
// BR-CO-15 at /Invoice: Invoice total amount with VAT (BT-112) = …
//   https://xmlvalid.com/rules/BR-CO-15
```

Your own ISO Schematron rules (query binding `xslt2` or `xslt3`) go along as `rules_file` and run after the schema and the profile's own rules:

```csharp
await using var rules = File.OpenRead("rules/our-checks.sch");
form.Add(new StreamContent(rules), "rules_file", "our-checks.sch");
```

## Reading the result

**`Status`**

`done`, `failed` (on our side, with `Error`) or `cancelled` once finished; `queued` or `running` before.

**`Result.Outcome`**

`valid`, `warnings`, `invalid` (the document broke the schema or the rules), `schema` (the schema itself could not be used), `input` (the document could not be read) or `failed`. `Valid` is true for the first two.

**`Result.Errors`, `Result.Warnings`**

Up to 500 each, with `Line` (0 for the whole document), `Level`, `Type` (`syntax`, `xsd`, `schematron`, `pdf`…), `Rule`, `Path`, `RuleUrl` and `HelpUrl`, a page on the message.

**`Result.Sha256`**

The SHA-256 of the file as sent, for an audit trail.

**`Links.Report`**

The result as an HTML report, to keep or send on.

## Errors and retries

A finding in the document is not an error of the request: it is in the result. A request that can't be served answers with a status and `{"error": {"code": "…", "message": "…"}}`:

| Status | Code | When |
|---|---|---|
| 401 | `unauthenticated` | No key, or a revoked one |
| 413 | `too_large` | Over your plan's size limit |
| 422 | `unknown_schema`, `invalid_request`… | An unknown slug, a bad URL, an invoice without a profile |
| 429 | `rate_limited` | Too many requests a minute: wait for `Retry-After` seconds and send it again |
| 429 | `quota_exceeded` | This month's validations are used up; don't retry |

A file stream can't be sent twice, so retry a `rate_limited` answer by waiting `response.Headers.RetryAfter` and calling `ValidateAsync` again, rather than with a handler that resends the same content. For tests against the real API without spending the month's validations, use a [test key](https://xmlvalid.com/docs/api#test-keys) (`xv_test_…`): the same checks, 10 validations a day outside the quota (50 on Pro).

## SOAP and WCF

For an older .NET Framework application or a BizTalk or ESB flow that speaks SOAP, the same validations run through the [SOAP endpoint](https://xmlvalid.com/docs/api#soap): point `dotnet-svcutil` or Add Service Reference at its WSDL, `https://xmlvalid.com/api/soap/v1?wsdl`, and call `Validate` with the document in Base64 and your key in the `ApiKey` header.

## Limits

|  | Free | Pro |
|---|---|---|
| API validations a month | 100 | 10,000 to 100,000 |
| Largest document | 10 MB | 1 GB |
| Requests a minute | 10 | 120 |
| Saved schemas | 25 | 200 |
| Rules kept with a saved schema, webhooks, report links | No | Yes |

A document in a `.zip` counts as one validation each. Schematron rules run on documents up to 50 MB, not counting the content of embedded attachments, PDFs up to 100 MB, archives up to 1,000 documents.

The HTTP API underneath is described in the [API reference](https://xmlvalid.com/docs/api). For scripts and CI, the [command-line client](https://xmlvalid.com/docs/ci) does the same from a terminal.
