, Mark Joseph Colibao, home

Read receipts with Azure Document Intelligence from ASP.NET Core

Send an image to the prebuilt receipt model, keyless, and map the fields and their confidence to your own types.

Written 2 min read

Azure Document Intelligence in Foundry Tools reads text and fields from images and PDFs. The prebuilt receipt model already knows what a merchant, a total and a date look like, so you don't train anything. It isn't a chat model: it returns labelled fields, and the SDK gives each one a confidence score.

What you need

  • A Document Intelligence resource. The free tier (F0) is enough to learn on: 500 pages a month, only the first 2 pages of each file, and files up to 4 MB.
  • Its custom-subdomain endpoint: https://<resource>.cognitiveservices.azure.com/. Regional endpoints don't support Microsoft Entra ID sign-in, so keyless calls need the custom subdomain.
  • The Cognitive Services User role on that resource, for your account and for the app's managed identity. That's the role the Foundry Tools authentication guide assigns. The SDK's README names Cognitive Services Data Reader instead, but that role only grants read data actions (Microsoft.CognitiveServices/*/read).
  • Packages: Azure.AI.DocumentIntelligence and Azure.Identity.

1. Register the client

C#
using Azure.AI.DocumentIntelligence;
using Azure.Identity;

builder.Services.AddSingleton(_ => new DocumentIntelligenceClient(
    new Uri(builder.Configuration["DocumentIntelligence:Endpoint"]!),
    new DefaultAzureCredential()));

2. Define what you keep

Only map the fields you use. If you don't need line items or payment details, don't read them out.

C#
public sealed record Field<T>(T Value, double Confidence);
public sealed record Money(decimal Amount, string? Currency);
public sealed record Receipt(Field<string>? Merchant, Field<Money>? Total, Field<DateOnly>? Date);

3. Analyze the upload

C#
using Azure;

app.MapPost("/receipts/scan", async (IFormFile file, DocumentIntelligenceClient client, CancellationToken ct) =>
{
    if (file.Length > 4 * 1024 * 1024) return Results.BadRequest("Max 4 MB.");

    await using var stream = file.OpenReadStream();
    var content = await BinaryData.FromStreamAsync(stream, ct);

    // Page 1 only: analysis is billed per page.
    var request = new AnalyzeDocumentOptions("prebuilt-receipt", content) { Pages = "1" };
    Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, request, ct);

    var doc = operation.Value.Documents.FirstOrDefault();
    if (doc is null) return Results.Ok(new Receipt(null, null, null));

    DocumentField? Get(string name) => doc.Fields.TryGetValue(name, out var f) ? f : null;
    static double Conf(DocumentField f) => f.Confidence ?? 0;

    var merchant = Get("MerchantName") is { } m && (m.ValueString ?? m.Content) is { Length: > 0 } name
        ? new Field<string>(name, Conf(m)) : null;

    var total = Get("Total") switch
    {
        { ValueCurrency: { } c } f => new Field<Money>(new Money((decimal)c.Amount, c.CurrencyCode), Conf(f)),
        { ValueDouble: { } d } f => new Field<Money>(new Money((decimal)d, null), Conf(f)),
        _ => null,
    };

    var date = Get("TransactionDate") is { ValueDate: { } d2 } df
        ? new Field<DateOnly>(DateOnly.FromDateTime(d2.DateTime), Conf(df)) : null;

    return Results.Ok(new Receipt(merchant, total, date));
}).DisableAntiforgery();

Analysis is a long-running operation on the service side. WaitUntil.Completed makes the call return only once the result is ready.

.DisableAntiforgery() is there because minimal API form binding, a file upload included, gets antiforgery protection by default. Turn it off only when the endpoint is secured with a bearer token or an API key. If the browser signs in with a cookie, keep the check.

4. Use the confidence

A field's value is the model's reading, not a checked fact. Use its confidence to decide what the user should check:

  • Above your threshold (for example 0.7): fill it in.
  • Below it: fill it in but mark it check this.
  • Missing: leave it empty for the user to type.
Example: one receipt's fields against a 0.7 threshold
  • MerchantName.ValueString
    Corner Café
    0.94
    Fill in
  • Total.ValueDouble
    125.00
    0.61
    Check this
  • TransactionDate.ValueDate
    not found
    –
    Leave empty

threshold 0.7

Don't save the result until the user confirms it.

Things I'd watch for

  • Currency. The receipt model lists Total as a number with no currency code, so Money.Currency is often null. The code also accepts a currency value, the type the SDK's own samples read amounts with.
  • Privacy. The file is sent to Azure for analysis. Don't log the recognized text, and don't keep the file if you don't need it.
  • Limits. Cap the scans per user per day, so one user can't use up the free tier.
  • Errors. Catch RequestFailedException and AuthenticationFailedException, and let the user type the receipt by hand when scanning is down.

Sources