Context
Validating uploads by MIME type (“PDF only”) in a browser client and an ASP.NET Core API. A user renamed a real PDF and lost the .pdf ending — the upload was refused as “not a PDF”.
Insight
- In the browser,
File.typeis derived from the file extension, not the bytes. A PDF namedreporthastype === ''(orapplication/octet-stream). - The multipart part’s
Content-Typethe server receives inherits that guess, so a server check on the content type refuses it too. - In ASP.NET Core minimal APIs there can be two gates: an endpoint-level content-type check can return 415 before the handler’s own PDF check runs. Fix both.
<input accept="application/pdf,.pdf">greys out such files in the picker unless the user switches to “all files”.
Fix: decide by the leading magic bytes on both sides (%PDF- for PDF), then store and serve with the type you determined (application/pdf).
Snippets
Client (TypeScript):
async function isPdf(file: File): Promise<boolean> { const head = new Uint8Array(await file.slice(0, 5).arrayBuffer()); return new TextDecoder("ascii").decode(head) === "%PDF-";}Server (C#):
static async Task<bool> IsPdfAsync(Stream content, CancellationToken ct){ byte[] head = new byte[5]; int read = await content.ReadAtLeastAsync(head, 5, throwOnEndOfStream: false, ct); content.Position = 0; return read == 5 && head.AsSpan().SequenceEqual("%PDF-"u8);}Tests worth having: PDF without extension → accepted; PDF named .txt → accepted; text file named .pdf → refused.