---
title: "Read text from an uploaded image in ASP.NET Core"
url: https://recursiveai.org/oneocr/cookbook/ocr-image-upload-in-aspnet-core/
description: "Use OneOcr in a C# minimal API to read a bounded multipart image upload and return the recognized text. Try it locally with the included PNG."
version: "1.1.0"
---

Send the included `hours.png` as a multipart upload to the running C# example. It returns plain text.

```shell
dotnet add package RecursiveAI.OneOcr
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

Unzip [the example](https://recursiveai.org/oneocr/cookbook/ocr-image-upload-in-aspnet-core/ocr-image-upload-in-aspnet-core.zip), then `dotnet run`.

In a second terminal in the same folder, send the image:

```shell
curl -F image=@hours.png \
  'http://[::1]:5164/ocr'
```

```text
Library hours
Monday to Friday
```


## The full program

Start with `dotnet new web` if you’re creating the project yourself. `RecursiveAI.OneOcr` brings in the bundled recognizer through `RecursiveAI.OneOcr.Models`. `hours.png` shows the two lines printed above.

```csharp
using Microsoft.AspNetCore.Http.Features;
using OneOcr;

const int maxFile = 2 * 1024 * 1024;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
    options.Limits.MaxRequestBodySize = maxFile + 64 * 1024);
builder.Services.Configure<FormOptions>(options =>
    options.MultipartBodyLengthLimit = maxFile + 64 * 1024);

var engine = OcrEngine.LoadBundled(new OcrLimits
{
    MaxImagePixels = 4_000_000,
    MaxPagesPerCall = 1 // Read each upload as one page.
});
var app = builder.Build();
app.MapPost("/ocr", ReadImage).DisableAntiforgery();
app.Run("http://[::1]:5164");

IResult ReadImage(IFormFile image, CancellationToken stop)
{
    if (image.Length == 0)
        return Results.BadRequest("Choose a non-empty image.");
    if (image.Length > maxFile)
        return Results.StatusCode(StatusCodes.Status413PayloadTooLarge);

    using var input = image.OpenReadStream();
    try
    {
        var page = engine.OcrPages(input, cancellationToken: stop).Single();
        return Results.Text(page.ToText().TrimEnd());
    }
    catch (OcrFormatException)
    {
        return Results.BadRequest("Unreadable image.");
    }
    catch (OcrLimitException)
    {
        return Results.BadRequest("Image exceeds the pixel or page limit.");
    }
}
```

The form part must be named `image`, matching the handler parameter. The response body is the text shown above, without a JSON wrapper. An unreadable image or an image beyond the OCR pixel or page cap gets HTTP 400; a file over 2 MiB that reaches the handler gets HTTP 413.

## Variations

If the client sets a media type on the file part explicitly, the upload command looks like this:

```shell
curl -F 'image=@hours.png;type=image/png' \
  'http://[::1]:5164/ocr'
```

It returns the same two lines. The decoder still has to recognize the bytes as an image.

## Related recipes

- [Extract text from an image in a console app](https://recursiveai.org/oneocr/cookbook/extract-text-from-image/)
- [Bound untrusted OCR input size](https://recursiveai.org/oneocr/cookbook/bound-untrusted-ocr-input-size/)
- [Reuse an OCR engine across workers](https://recursiveai.org/oneocr/cookbook/reuse-ocr-engine-across-workers/)

## The short answer

In an ASP.NET Core minimal API, bind a multipart file to `IFormFile`, check `Length`, and pass `OpenReadStream()` to `OcrEngine.OcrPages`. For a one-page upload, take the single `OcrPage` and return its `ToText()` as plain text. The example loads the bundled OCR engine once before serving requests; it doesn’t send the image to an external service. It’s a loopback-only demonstration for a command-line client, not a cookie-authenticated web form. For a browser-facing endpoint, configure [antiforgery for file uploads](https://learn.microsoft.com/aspnet/core/security/anti-request-forgery) instead of carrying over `DisableAntiforgery()`.

## Can OCR read an image?

Yes. OCR (optical character recognition) turns visible text in the pixels into characters the client can copy or search. This example expects one image frame and returns only its recognized text. `OcrPages` can read every frame of a multi-frame image, but this endpoint deliberately sets `MaxPagesPerCall = 1`. If a client needs positions or line structure, use the `OcrPage` result rather than trying to reconstruct boxes from the text response.

With `IFormFile` the server binds and buffers the multipart file before the handler reads its stream; calling `OpenReadStream()` does not make the request an unbuffered streaming endpoint. The example caps the request body in Kestrel and caps multipart section buffering via `FormOptions`. The request ceiling is slightly above the file ceiling to make room for multipart headers and boundaries. For the buffering behavior, see the [ASP.NET Core file upload documentation](https://learn.microsoft.com/aspnet/core/mvc/models/file-uploads).

## How do I pull data from an image?

Start by deciding whether the caller needs plain recognized text or named fields. For plain text, `ToText()` gives the client a body it can display without having to interpret the page model. For a form where labels and values matter, retain the recognized page and its word positions for extraction; don’t try to identify a column based only on spaces in the response.

A file-size check alone doesn’t control OCR work. A compressed image can be small on the wire but expand into many pixels. OneOcr checks the configured pixel and frame limits before decoding pixels when you use the path, stream, or bytes overload of `OcrPages`. Pass the request cancellation token as well, so the OCR call can observe cancellation if the request ends. Choose the limits and concurrency for your own workload rather than accepting arbitrary uploads by default.
