{"record":{"id":"4c4ee4a130596f5c","repo":"fullstackhero/dotnet-starter-kit","slug":"file-exceeds-max-size-of-rules-maxsizeinmb-mb","errorCode":null,"errorMessage":"File exceeds max size of {rules.MaxSizeInMB} MB.","messagePattern":"File exceeds max size of (.+?) MB\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/BuildingBlocks/Storage/Local/LocalStorageService.cs","lineNumber":49,"sourceCode":"    }\n\n    public async Task<string> UploadAsync<T>(FileUploadRequest request, FileType fileType, CancellationToken cancellationToken = default)\n        where T : class\n    {\n        ArgumentNullException.ThrowIfNull(request);\n\n        var rules = FileTypeMetadata.GetRules(fileType);\n        var extension = Path.GetExtension(request.FileName);\n\n        if (string.IsNullOrWhiteSpace(extension) ||\n            !rules.AllowedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))\n        {\n            throw new InvalidOperationException($\"File type '{extension}' is not allowed. Allowed: {string.Join(\", \", rules.AllowedExtensions)}\");\n        }\n\n        if (request.Data.Count > rules.MaxSizeInMB * 1024 * 1024)\n        {\n            throw new InvalidOperationException($\"File exceeds max size of {rules.MaxSizeInMB} MB.\");\n        }\n\n#pragma warning disable CA1308 // folder names are intentionally lower-case for URLs/paths\n        var folder = FolderSanitizer().Replace(typeof(T).Name.ToLowerInvariant(), \"_\");\n#pragma warning restore CA1308\n        var safeFileName = $\"{Guid.NewGuid():N}_{SanitizeFileName(request.FileName)}\";\n        var relativePath = Path.Combine(UploadBasePath, folder, safeFileName);\n        var fullPath = Path.Combine(_rootPath, relativePath);\n\n        Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);\n\n        await File.WriteAllBytesAsync(fullPath, request.Data.ToArray(), cancellationToken);\n\n        return relativePath.Replace(\"\\\\\", \"/\", StringComparison.Ordinal); // Normalize for URLs\n    }\n\n    public Task<FileDownloadResponse?> DownloadAsync(string path, CancellationToken cancellationToken = default)\n    {","sourceCodeStart":31,"sourceCodeEnd":67,"githubUrl":"https://github.com/fullstackhero/dotnet-starter-kit/blob/3f2959e683e9f83f13e55e1678c9119f63c7e8e5/src/BuildingBlocks/Storage/Local/LocalStorageService.cs#L31-L67","documentation":"LocalStorageService.UploadAsync enforces the per-FileType size cap rules.MaxSizeInMB by checking request.Data.Count against the limit in bytes. Files larger than the cap throw InvalidOperationException before the blob is written to disk. This protects local disk from oversized payloads.","triggerScenarios":"UploadAsync called with request.Data whose byte count exceeds rules.MaxSizeInMB * 1024 * 1024 for the given FileType.","commonSituations":"Users uploading large videos or high-resolution images; batch/import tools streaming whole files into memory; MaxSizeInMB tightened in config without updating client-side limits; frontend not enforcing a pre-upload size check.","solutions":["Upload a smaller file or compress/downscale before upload.","Raise rules.MaxSizeInMB for the FileType in FileTypeMetadata if the cap is too strict.","Chunk or stream large files instead of a single UploadAsync call.","Check file size client-side and block the upload before it starts."],"exampleFix":"// before: no size check\nawait storage.UploadAsync(new UploadRequest { FileName = name, FileType = FileType.Video, Data = hugeFile });\n\n// after\nconst long maxBytes = 50 * 1024 * 1024;\nif (hugeFile.Length > maxBytes) return BadRequest(\"Video exceeds 50 MB limit\");\nawait storage.UploadAsync(new UploadRequest { FileName = name, FileType = FileType.Video, Data = hugeFile });","handlingStrategy":"validation","validationCode":"var rules = FileTypeMetadata.GetRules(fileType);\nvar maxBytes = (long)rules.MaxSizeInMB * 1024 * 1024;\nif (data.Length > maxBytes)\n    throw new ArgumentException($\"File exceeds max size of {rules.MaxSizeInMB} MB.\");","typeGuard":"bool IsWithinSizeLimit(long byteCount, FileTypeRules rules) => byteCount <= (long)rules.MaxSizeInMB * 1024 * 1024;","tryCatchPattern":"try {\n    await storage.UploadAsync(request);\n} catch (InvalidOperationException ex) when (ex.Message.Contains(\"exceeds max size\")) {\n    return Results.StatusCode(413);\n}","preventionTips":["Enforce the same MaxSizeInMB limit client-side before upload.","Compress images/video or split large imports into chunks.","Document size limits per file type in API docs."],"tags":["storage","file-size","validation"],"backgroundTag":"file-size-limit-exceeded","analyzedSha":"3f2959e683e9f83f13e55e1678c9119f63c7e8e5","analyzedAt":"2026-09-15T22:20:53.684Z","contentChangedAt":"2026-09-15T22:20:53.684Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}