How to Build a Secure File Upload API in ASP.NET Core 10 Using Azure Blob Storage (2026)

A secure upload endpoint authenticates the caller, bounds request size, and stores the file in a private quarantine area before any consumer can retrieve it. In this example, ASP.NET Core reads multipart data incrementally into a temporary file, verifies a PNG signature and sends the result to a private Azure Blob container. The success response says the upload is quarantined. It does not certify that the image is safe.

Follow the quarantine boundary

The API bounds and checks the upload before placing it in private quarantine. A separate scanner controls promotion.
The API bounds and checks the upload before placing it in private quarantine. A separate scanner controls promotion.

The request path does cheap validation and stores the bytes. A separate trusted process should perform full file decoding, malware scanning and policy checks. Consumers should use a separate approved store or a trusted approval record. Keep the upload identity separate from the scanner and download identity so each has only its necessary access.

Microsoft ASP.NET Core upload guidance · Azure Blob upload with .NET

Prepare Azure and ASP.NET Core

Install .NET 10 and create a minimal web project. Add Azure.Storage.Blobs, Azure.Identity and the .NET 10 line of Microsoft.AspNetCore.Authentication.JwtBearer. Create a private quarantine container. Disable anonymous access at the storage account when your environment permits it. Assign the application identity an appropriate blob data role scoped to the quarantine container. For a lab, Storage Blob Data Contributor supplies upload access. In production, review a narrowly scoped role and separate operational access.

Set Storage__QuarantineUri to the container HTTPS URL without a SAS or key. Use a managed identity in the hosted environment. For local testing, sign in with a development identity that has the required access. Set Auth__Authority and Auth__Audience to your trusted token issuer and API audience. Configure an Upload.Write role in the identity contract.

Implement bounded multipart ingestion

Program.cs
using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;

const long MaxFile = 8 * 1024 * 1024;
const long MaxRequest = MaxFile + 64 * 1024;
var b = WebApplication.CreateBuilder(args);
b.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = MaxRequest);
b.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
    o.Authority = b.Configuration["Auth:Authority"];
    o.Audience = b.Configuration["Auth:Audience"];
});
b.Services.AddAuthorization(o =>
    o.AddPolicy("Upload", p => p.RequireRole("Upload.Write")));
var uri = b.Configuration["Storage:QuarantineUri"]
    ?? throw new InvalidOperationException("Set Storage:QuarantineUri.");
b.Services.AddSingleton(new BlobContainerClient(new Uri(uri), new DefaultAzureCredential()));

var app = b.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/uploads", async Task<IResult> (
    HttpRequest request, BlobContainerClient container, CancellationToken ct) =>
{
    if (!MediaTypeHeaderValue.TryParse(request.ContentType, out var type)
        || !string.Equals(type.MediaType.Value, "multipart/form-data",
            StringComparison.OrdinalIgnoreCase))
        return Results.StatusCode(415);

    var boundary = HeaderUtilities.RemoveQuotes(type.Boundary).Value;
    if (string.IsNullOrWhiteSpace(boundary) || boundary.Length > 70)
        return Results.BadRequest("Invalid multipart boundary.");

    string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
    try
    {
        var reader = new MultipartReader(boundary, request.Body)
        {
            HeadersCountLimit = 8,
            HeadersLengthLimit = 8192,
            BodyLengthLimit = MaxRequest
        };
        var section = await reader.ReadNextSectionAsync(ct);
        if (section is null
            || !ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var cd)
            || !string.Equals(cd.DispositionType.Value, "form-data", StringComparison.OrdinalIgnoreCase)
            || HeaderUtilities.RemoveQuotes(cd.Name).Value != "file"
            || (!cd.FileName.HasValue && !cd.FileNameStar.HasValue))
            return Results.BadRequest("Send one multipart file named file.");

        await using var temp = new FileStream(tempPath, FileMode.CreateNew,
            FileAccess.ReadWrite, FileShare.None, 65536,
            FileOptions.Asynchronous | FileOptions.DeleteOnClose);
        var buffer = new byte[65536];
        long total = 0;
        int count;
        while ((count = await section.Body.ReadAsync(buffer.AsMemory(), ct)) > 0)
        {
            total += count;
            if (total > MaxFile) return Results.StatusCode(413);
            await temp.WriteAsync(buffer.AsMemory(0, count), ct);
        }
        if (await reader.ReadNextSectionAsync(ct) is not null)
            return Results.BadRequest("Only one part is allowed.");

        var png = new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 };
        if (temp.Length <= png.Length) return Results.StatusCode(415);
        temp.Position = 0;
        var prefix = new byte[png.Length];
        await temp.ReadExactlyAsync(prefix, ct);
        if (!prefix.AsSpan().SequenceEqual(png)) return Results.StatusCode(415);

        var id = Guid.NewGuid().ToString("N");
        temp.Position = 0;
        await container.GetBlobClient(id).UploadAsync(temp, new BlobUploadOptions
        {
            Conditions = new BlobRequestConditions { IfNoneMatch = Azure.ETag.All },
            HttpHeaders = new BlobHttpHeaders { ContentType = "application/octet-stream" }
        }, ct);
        return Results.Accepted(value: new { id, status = "quarantined" });
    }
    catch (BadHttpRequestException e) when (e.StatusCode == 413)
    {
        return Results.StatusCode(413);
    }
    catch (InvalidDataException)
    {
        return Results.BadRequest("Malformed multipart request.");
    }
    catch (Azure.RequestFailedException e)
    {
        app.Logger.LogWarning("Quarantine storage failure: {Status}", e.Status);
        return Results.StatusCode(503);
    }
}).RequireAuthorization("Upload");
app.Run();

The server ignores the client filename and uses a random object ID. It only accepts a single file part named file. It does not use form model binding, so application code consumes the request stream directly. The temporary file bounds memory use and allows inspection before making the storage request. It also requires disk capacity and protection against many concurrent uploads. This sample limits the request globally to about 8 MiB plus framing overhead. Larger file designs may use staged blocks or narrowly scoped direct-to-storage uploads, with a quarantine and finalization protocol.

A PNG signature can reject obvious mismatches. It cannot establish that the full file is a valid or safe PNG. A malicious or malformed file can begin with those bytes. Scan and decode with resource limits, then set the approved content type only when the trusted process verifies it. Do not serve quarantine objects.

Test accepted and rejected uploads

Send a multipart POST to /uploads with a valid access token and a file part named file. A small PNG should return 202 with an ID and "status":"quarantined". Confirm the blob exists in the private container and that an anonymous browser cannot read it.

Test Expected result
Authenticated upload of a small PNG 202, quarantined
Plain JSON body 415
Text file renamed to PNG 415
More than one multipart section 400
Body or file over the configured limit 413, possibly generated by the proxy
Missing token or missing upload role 401 or 403 respectively

Also check that a failed upload does not create a readable approved object. Test cloud permissions, storage outages and cancellation separately. A local smoke test with a fixture OIDC issuer confirmed 401, 403, and 415 for both an unsupported request media type and a false PNG signature. Azure upload, scanner integration, and the oversize path remain untested.

Production controls and FAQs

What if a proxy returns 413 first? Align Kestrel, reverse proxy and load-balancer size limits and document which layer rejects oversized requests. Add per-user quotas and a concurrency limit to protect temporary disk.

How do approved files become downloadable? Use an authorized application route, or issue a short-lived read-only user delegation SAS for an approved object after checking access. Keep quarantine outside that path. Azure user delegation SAS

Does this scan for malware? The API only quarantines. Integrate a scanner and define retry, duplicate-event, rejection and expiry behavior before building a public download path. Review Defender for Storage malware scanning or a scanner appropriate to your environment.

What should I log? Log the generated object ID, actor reference, outcome and timing. Avoid file contents, tokens and raw filenames. Keep client errors generic. The ASP.NET PB exception handling guide shows a broader API error strategy.

An upload is complete for consumers only after the trusted approval step. Use that distinction in API status names and storage permissions.

Comments