[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D0KEX6WE3YVCNWPDTV9TPT":3,"skill-same:01M7D0KEX6WE3YVCNWPDTV9TPT":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7D0KEX6WE3YVCNWPDTV9TPT","minimal-api-file-upload",null,"File upload endpoints in ASP.NET minimal APIs (.NET 8+)","itsmejay18\u002FAI-Skills-for-My-Development-Stack","itsmejay18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F167779943?v=4","01M7CZRFC6DDZA5V2CX8WDSZED","Jay Jemino Ababon ","01M7CZRFCVRNW1SFHSQXEJ3CQN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F02-CSharp-WPF-Desktop-Development\u002Fminimal-api-file-upload\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: minimal-api-file-upload\ndescription: File upload endpoints in ASP.NET minimal APIs (.NET 8+)\nlicense: MIT\n---\n\n# Implementing File Uploads in ASP.NET Core Minimal APIs\n\n## When to Use\n- File upload endpoints in ASP.NET Core minimal APIs (.NET 8+)\n- Handling IFormFile or IFormFileCollection parameters\n- When you need size limits, content type validation, or streaming large files\n\n## When Not to Use\n- MVC controllers → `[FromForm] IFormFile` works directly with attributes\n- Simple JSON body → no file upload needed\n- Very large files (> 1GB) → use streaming with `MultipartReader` instead\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| File parameter(s) | Yes | IFormFile or IFormFileCollection |\n| Size limits | Yes | Max file\u002Frequest size |\n| Allowed types | No | Content type or extension restrictions |\n\n## Workflow\n\n### Step 1: CRITICAL — Understand IFormFile Binding in Minimal APIs\n\n```csharp\n\u002F\u002F In .NET 8+ minimal APIs, IFormFile binds automatically from multipart\u002Fform-data\n\u002F\u002F when it is the only complex parameter.\napp.MapPost(\"\u002Fupload\", (IFormFile file) => ...);\n\n\u002F\u002F CRITICAL: When you mix files with other form fields, use [FromForm] on all\n\u002F\u002F form-bound parameters (or group them into a single [FromForm] DTO).\napp.MapPost(\"\u002Fupload-with-metadata\",\n    ([FromForm] IFormFile file, [FromForm] string description) =>\n{\n    return Results.Ok(new { file.FileName, Description = description });\n});\n\n\u002F\u002F Multiple files: IFormFileCollection also binds automatically from multipart\u002Fform-data.\n\u002F\u002F You only need [FromForm] if you mix it with other form fields, as shown above.\napp.MapPost(\"\u002Fupload-multiple\", (IFormFileCollection files) =>\n{\n    return Results.Ok(files.Select(f => new { f.FileName, f.Length }));\n});\n```\n\n### Step 2: CRITICAL — File Size Limits Are Separate from Request Size Limits\n\n```csharp\n\u002F\u002F CRITICAL: There are TWO different size limits and you need to configure BOTH\n\n\u002F\u002F 1. Request body size limit (Kestrel level) — default is 30MB\nbuilder.WebHost.ConfigureKestrel(options =>\n{\n    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; \u002F\u002F 10 MB\n});\n\n\u002F\u002F 2. Form options — multipart body length limit — default is 128MB\nbuilder.Services.Configure\u003CFormOptions>(options =>\n{\n    options.MultipartBodyLengthLimit = 10 * 1024 * 1024; \u002F\u002F 10 MB\n    options.ValueLengthLimit = 1024 * 1024; \u002F\u002F 1 MB for form values\n    options.MultipartHeadersLengthLimit = 16384; \u002F\u002F 16 KB for section headers\n});\n\n\u002F\u002F COMMON MISTAKE: Only increasing Kestrel MaxRequestBodySize\n\u002F\u002F upload still fails because FormOptions.MultipartBodyLengthLimit is exceeded\n\n\u002F\u002F COMMON MISTAKE: Only increasing FormOptions\n\u002F\u002F upload fails with \"Request body too large\" from Kestrel before reaching form parsing\n\n\u002F\u002F CRITICAL: Per-endpoint override with RequestSizeLimit attribute\napp.MapPost(\"\u002Fupload-large\", [RequestSizeLimit(200_000_000)] (IFormFile file) =>\n{\n    return Results.Ok(new { file.FileName, file.Length });\n});\n\n\u002F\u002F CRITICAL: To disable the limit entirely (for streaming):\napp.MapPost(\"\u002Fupload-unlimited\", [DisableRequestSizeLimit] async (HttpContext context) =>\n{\n    \u002F\u002F Handle manually\n});\n```\n\n### Step 3: CRITICAL — Anti-Forgery Auto-Validates Form Uploads in .NET 8+\n\n```csharp\n\u002F\u002F CRITICAL: In .NET 8+ with UseAntiforgery(), ALL form-bound endpoints\n\u002F\u002F automatically validate anti-forgery tokens, INCLUDING file uploads\n\nbuilder.Services.AddAntiforgery();\nvar app = builder.Build();\napp.UseAntiforgery();\n\n\u002F\u002F This endpoint now REQUIRES an anti-forgery token:\napp.MapPost(\"\u002Fupload\", (IFormFile file) => Results.Ok(file.FileName));\n\u002F\u002F Without the token → 400 Bad Request\n\n\u002F\u002F CRITICAL: For API-only file uploads (no anti-forgery needed), opt out:\napp.MapPost(\"\u002Fapi\u002Fupload\", (IFormFile file) => Results.Ok(file.FileName))\n    .DisableAntiforgery();  \u002F\u002F CRITICAL: Must explicitly opt out\n\n\u002F\u002F COMMON MISTAKE: Getting 400 errors on file uploads and not realizing\n\u002F\u002F it's because UseAntiforgery() is in the pipeline\n\n\u002F\u002F WARNING: DisableAntiforgery() is safe for unauthenticated endpoints and\n\u002F\u002F endpoints using JWT bearer authentication. However, for endpoints\n\u002F\u002F authenticated with cookies, disabling antiforgery removes CSRF protection\n\u002F\u002F and exposes the endpoint to cross-site request forgery attacks.\n\u002F\u002F For cookie-authenticated endpoints, include a valid antiforgery token instead.\n```\n\n### Step 4: CRITICAL — Validate File Content, Not Just Extension\n\n```csharp\napp.MapPost(\"\u002Fupload\", async (IFormFile file) =>\n{\n    \u002F\u002F CRITICAL: Check content type AND file signature (magic bytes)\n    \u002F\u002F NEVER trust file extension alone — it can be spoofed\n\n    \u002F\u002F Allow only JPEG\u002FPNG by default. To support more (e.g., GIF),\n    \u002F\u002F add the MIME type here AND validate its magic bytes below.\n    var allowedTypes = new[] { \"image\u002Fjpeg\", \"image\u002Fpng\" };\n    if (!allowedTypes.Contains(file.ContentType, StringComparer.OrdinalIgnoreCase))\n        return Results.BadRequest(\"File type not allowed\");\n\n    \u002F\u002F CRITICAL: Check magic bytes for file type verification\n    using var stream = file.OpenReadStream();\n    var header = new byte[8];\n    var bytesRead = await stream.ReadAsync(header, 0, header.Length);\n    if (bytesRead \u003C 4)\n        return Results.BadRequest(\"File content is too short or invalid\");\n\n    \u002F\u002F JPEG: FF D8 FF\n    \u002F\u002F PNG: 89 50 4E 47\n    var isJpeg = header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF;\n    var isPng = header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47;\n\n    \u002F\u002F Determine the actual content type from magic bytes\n    string? detectedContentType = isJpeg ? \"image\u002Fjpeg\" : isPng ? \"image\u002Fpng\" : null;\n    if (detectedContentType is null)\n        return Results.BadRequest(\"File content is not a supported image format (only JPEG and PNG are allowed).\");\n\n    \u002F\u002F Ensure the declared Content-Type matches what the magic bytes detected\n    if (!string.Equals(file.ContentType, detectedContentType, StringComparison.OrdinalIgnoreCase))\n        return Results.BadRequest(\"File content type does not match the declared ContentType header.\");\n\n    \u002F\u002F CRITICAL: Never use the user-provided filename directly for the save path — it can\n    \u002F\u002F contain path traversal characters (e.g., \"..\u002F..\u002F..\u002Fetc\u002Fpasswd\").\n    \u002F\u002F Generate a safe filename; derive the extension from validated content, not user input.\n    var extension = detectedContentType == \"image\u002Fjpeg\" ? \".jpg\" : \".png\";\n    var safeFileName = $\"{Guid.NewGuid()}{extension}\";\n    \u002F\u002F NEVER: var path = Path.Combine(\"uploads\", file.FileName);     \u002F\u002F Path traversal!\n\n    var filePath = Path.Combine(\"uploads\", safeFileName);\n    Directory.CreateDirectory(\"uploads\");\n    stream.Position = 0;\n    using var fileStream = File.Create(filePath);\n    await stream.CopyToAsync(fileStream);\n\n    return Results.Ok(new { FileName = safeFileName, file.Length });\n});\n```\n\n### Step 5: CRITICAL — Streaming Large Files Without Buffering\n\n```csharp\n\u002F\u002F CRITICAL: IFormFile relies on multipart form parsing that buffers content in memory\n\u002F\u002F (up to a threshold) then spills to temp files on disk. For very large uploads,\n\u002F\u002F this overhead is unnecessary if you can process the data in chunks.\n\u002F\u002F Use MultipartReader to stream directly — e.g., to a final storage location —\n\u002F\u002F without buffering the entire file first.\n\napp.MapPost(\"\u002Fupload-stream\",\n    [DisableRequestSizeLimit]\n    async (HttpContext context) =>\n{\n    \u002F\u002F Extract the multipart boundary from the Content-Type header\n    var contentType = context.Request.ContentType;\n    if (contentType == null)\n        return Results.BadRequest(\"Missing Content-Type\");\n\n    \u002F\u002F Safely parse the Content-Type header to avoid FormatException from MediaTypeHeaderValue.Parse\n    if (!MediaTypeHeaderValue.TryParse(contentType, out var mediaType))\n        return Results.BadRequest(\"Invalid Content-Type\");\n\n    var boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value;\n    if (string.IsNullOrWhiteSpace(boundary))\n        return Results.BadRequest(\"Not a multipart request\");\n\n    var reader = new MultipartReader(boundary, context.Request.Body);\n\n    \u002F\u002F CRITICAL: ReadNextSectionAsync returns null when there are no more sections\n    while (await reader.ReadNextSectionAsync() is { } section)\n    {\n        \u002F\u002F Parse Content-Disposition to identify file sections\n        if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition))\n            continue;\n\n        if (contentDisposition.DispositionType.Equals(\"form-data\")\n            && !string.IsNullOrEmpty(contentDisposition.FileName.Value))\n        {\n            \u002F\u002F Sanitize the user-provided filename to prevent path traversal\n            var originalFileName = contentDisposition.FileName.Value ?? string.Empty;\n            var sanitizedFileName = Path.GetFileName(originalFileName.Trim('\"'));\n            var safeFile = $\"{Guid.NewGuid()}\";\n\n            \u002F\u002F CRITICAL: Stream directly to disk — avoids buffering in memory\n            Directory.CreateDirectory(\"uploads\");\n            using var fileStream = File.Create(Path.Combine(\"uploads\", safeFile));\n            await section.Body.CopyToAsync(fileStream);\n        }\n    }\n\n    return Results.Ok(\"Uploaded\");\n}).DisableAntiforgery();\n\n\u002F\u002F COMMON MISTAKE: Using IFormFile for very large files\n\u002F\u002F Multipart form parsing can buffer large uploads and consume memory\u002Fdisk.\n\u002F\u002F Use MultipartReader for streaming directly to storage.\n```\n\n## Common Mistakes\n\n1. **Only configuring one size limit**: Must configure BOTH Kestrel `MaxRequestBodySize` AND `FormOptions.MultipartBodyLengthLimit`.\n2. **400 errors from anti-forgery**: In .NET 8+, `UseAntiforgery()` auto-validates form uploads. Use `.DisableAntiforgery()` for API endpoints (safe for JWT\u002Funauthenticated; do NOT disable for cookie-authenticated endpoints).\n3. **Trusting file.FileName**: User-provided filename can contain path traversal. Generate a safe filename with `Guid.NewGuid()` and derive the extension from validated content.\n4. **Trusting Content-Type only**: Content type is client-spoofable. Always check magic bytes for actual file type verification.\n5. **Using IFormFile for very large files**: Multipart form parsing buffers with a memory threshold and spills to temp files. Use `MultipartReader` to stream data in chunks directly to storage without buffering the entire file.\n6. **Deriving file extension from user input**: Prefer deriving the extension from the validated content type or magic bytes rather than `Path.GetExtension(file.FileName)`. If the original extension must be preserved, validate it against the detected content type.\n","# Implementing File Uploads in ASP.NET Core Minimal APIs\n\n## When to Use\n- File upload endpoints in ASP.NET Core minimal APIs (.NET 8+)\n- Handling IFormFile or IFormFileCollection parameters\n- When you need size limits, content type validation, or streaming large files\n\n## When Not to Use\n- MVC controllers → `[FromForm] IFormFile` works directly with attributes\n- Simple JSON body → no file upload needed\n- Very large files (> 1GB) → use streaming with `MultipartReader` instead\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| File parameter(s) | Yes | IFormFile or IFormFileCollection |\n| Size limits | Yes | Max file\u002Frequest size |\n| Allowed types | No | Content type or extension restrictions |\n\n## Workflow\n\n### Step 1: CRITICAL — Understand IFormFile Binding in Minimal APIs\n\n```csharp\n\u002F\u002F In .NET 8+ minimal APIs, IFormFile binds automatically from multipart\u002Fform-data\n\u002F\u002F when it is the only complex parameter.\napp.MapPost(\"\u002Fupload\", (IFormFile file) => ...);\n\n\u002F\u002F CRITICAL: When you mix files with other form fields, use [FromForm] on all\n\u002F\u002F form-bound parameters (or group them into a single [FromForm] DTO).\napp.MapPost(\"\u002Fupload-with-metadata\",\n    ([FromForm] IFormFile file, [FromForm] string description) =>\n{\n    return Results.Ok(new { file.FileName, Description = description });\n});\n\n\u002F\u002F Multiple files: IFormFileCollection also binds automatically from multipart\u002Fform-data.\n\u002F\u002F You only need [FromForm] if you mix it with other form fields, as shown above.\napp.MapPost(\"\u002Fupload-multiple\", (IFormFileCollection files) =>\n{\n    return Results.Ok(files.Select(f => new { f.FileName, f.Length }));\n});\n```\n\n### Step 2: CRITICAL — File Size Limits Are Separate from Request Size Limits\n\n```csharp\n\u002F\u002F CRITICAL: There are TWO different size limits and you need to configure BOTH\n\n\u002F\u002F 1. Request body size limit (Kestrel level) — default is 30MB\nbuilder.WebHost.ConfigureKestrel(options =>\n{\n    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; \u002F\u002F 10 MB\n});\n\n\u002F\u002F 2. Form options — multipart body length limit — default is 128MB\nbuilder.Services.Configure\u003CFormOptions>(options =>\n{\n    options.MultipartBodyLengthLimit = 10 * 1024 * 1024; \u002F\u002F 10 MB\n    options.ValueLengthLimit = 1024 * 1024; \u002F\u002F 1 MB for form values\n    options.MultipartHeadersLengthLimit = 16384; \u002F\u002F 16 KB for section headers\n});\n\n\u002F\u002F COMMON MISTAKE: Only increasing Kestrel MaxRequestBodySize\n\u002F\u002F upload still fails because FormOptions.MultipartBodyLengthLimit is exceeded\n\n\u002F\u002F COMMON MISTAKE: Only increasing FormOptions\n\u002F\u002F upload fails with \"Request body too large\" from Kestrel before reaching form parsing\n\n\u002F\u002F CRITICAL: Per-endpoint override with RequestSizeLimit attribute\napp.MapPost(\"\u002Fupload-large\", [RequestSizeLimit(200_000_000)] (IFormFile file) =>\n{\n    return Results.Ok(new { file.FileName, file.Length });\n});\n\n\u002F\u002F CRITICAL: To disable the limit entirely (for streaming):\napp.MapPost(\"\u002Fupload-unlimited\", [DisableRequestSizeLimit] async (HttpContext context) =>\n{\n    \u002F\u002F Handle manually\n});\n```\n\n### Step 3: CRITICAL — Anti-Forgery Auto-Validates Form Uploads in .NET 8+\n\n```csharp\n\u002F\u002F CRITICAL: In .NET 8+ with UseAntiforgery(), ALL form-bound endpoints\n\u002F\u002F automatically validate anti-forgery tokens, INCLUDING file uploads\n\nbuilder.Services.AddAntiforgery();\nvar app = builder.Build();\napp.UseAntiforgery();\n\n\u002F\u002F This endpoint now REQUIRES an anti-forgery token:\napp.MapPost(\"\u002Fupload\", (IFormFile file) => Results.Ok(file.FileName));\n\u002F\u002F Without the token → 400 Bad Request\n\n\u002F\u002F CRITICAL: For API-only file uploads (no anti-forgery needed), opt out:\napp.MapPost(\"\u002Fapi\u002Fupload\", (IFormFile file) => Results.Ok(file.FileName))\n    .DisableAntiforgery();  \u002F\u002F CRITICAL: Must explicitly opt out\n\n\u002F\u002F COMMON MISTAKE: Getting 400 errors on file uploads and not realizing\n\u002F\u002F it's because UseAntiforgery() is in the pipeline\n\n\u002F\u002F WARNING: DisableAntiforgery() is safe for unauthenticated endpoints and\n\u002F\u002F endpoints using JWT bearer authentication. However, for endpoints\n\u002F\u002F authenticated with cookies, disabling antiforgery removes CSRF protection\n\u002F\u002F and exposes the endpoint to cross-site request forgery attacks.\n\u002F\u002F For cookie-authenticated endpoints, include a valid antiforgery token instead.\n```\n\n### Step 4: CRITICAL — Validate File Content, Not Just Extension\n\n```csharp\napp.MapPost(\"\u002Fupload\", async (IFormFile file) =>\n{\n    \u002F\u002F CRITICAL: Check content type AND file signature (magic bytes)\n    \u002F\u002F NEVER trust file extension alone — it can be spoofed\n\n    \u002F\u002F Allow only JPEG\u002FPNG by default. To support more (e.g., GIF),\n    \u002F\u002F add the MIME type here AND validate its magic bytes below.\n    var allowedTypes = new[] { \"image\u002Fjpeg\", \"image\u002Fpng\" };\n    if (!allowedTypes.Contains(file.ContentType, StringComparer.OrdinalIgnoreCase))\n        return Results.BadRequest(\"File type not allowed\");\n\n    \u002F\u002F CRITICAL: Check magic bytes for file type verification\n    using var stream = file.OpenReadStream();\n    var header = new byte[8];\n    var bytesRead = await stream.ReadAsync(header, 0, header.Length);\n    if (bytesRead \u003C 4)\n        return Results.BadRequest(\"File content is too short or invalid\");\n\n    \u002F\u002F JPEG: FF D8 FF\n    \u002F\u002F PNG: 89 50 4E 47\n    var isJpeg = header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF;\n    var isPng = header[0] == 0x89 && header[1] == 0x50 && header[2] == 0x4E && header[3] == 0x47;\n\n    \u002F\u002F Determine the actual content type from magic bytes\n    string? detectedContentType = isJpeg ? \"image\u002Fjpeg\" : isPng ? \"image\u002Fpng\" : null;\n    if (detectedContentType is null)\n        return Results.BadRequest(\"File content is not a supported image format (only JPEG and PNG are allowed).\");\n\n    \u002F\u002F Ensure the declared Content-Type matches what the magic bytes detected\n    if (!string.Equals(file.ContentType, detectedContentType, StringComparison.OrdinalIgnoreCase))\n        return Results.BadRequest(\"File content type does not match the declared ContentType header.\");\n\n    \u002F\u002F CRITICAL: Never use the user-provided filename directly for the save path — it can\n    \u002F\u002F contain path traversal characters (e.g., \"..\u002F..\u002F..\u002Fetc\u002Fpasswd\").\n    \u002F\u002F Generate a safe filename; derive the extension from validated content, not user input.\n    var extension = detectedContentType == \"image\u002Fjpeg\" ? \".jpg\" : \".png\";\n    var safeFileName = $\"{Guid.NewGuid()}{extension}\";\n    \u002F\u002F NEVER: var path = Path.Combine(\"uploads\", file.FileName);     \u002F\u002F Path traversal!\n\n    var filePath = Path.Combine(\"uploads\", safeFileName);\n    Directory.CreateDirectory(\"uploads\");\n    stream.Position = 0;\n    using var fileStream = File.Create(filePath);\n    await stream.CopyToAsync(fileStream);\n\n    return Results.Ok(new { FileName = safeFileName, file.Length });\n});\n```\n\n### Step 5: CRITICAL — Streaming Large Files Without Buffering\n\n```csharp\n\u002F\u002F CRITICAL: IFormFile relies on multipart form parsing that buffers content in memory\n\u002F\u002F (up to a threshold) then spills to temp files on disk. For very large uploads,\n\u002F\u002F this overhead is unnecessary if you can process the data in chunks.\n\u002F\u002F Use MultipartReader to stream directly — e.g., to a final storage location —\n\u002F\u002F without buffering the entire file first.\n\napp.MapPost(\"\u002Fupload-stream\",\n    [DisableRequestSizeLimit]\n    async (HttpContext context) =>\n{\n    \u002F\u002F Extract the multipart boundary from the Content-Type header\n    var contentType = context.Request.ContentType;\n    if (contentType == null)\n        return Results.BadRequest(\"Missing Content-Type\");\n\n    \u002F\u002F Safely parse the Content-Type header to avoid FormatException from MediaTypeHeaderValue.Parse\n    if (!MediaTypeHeaderValue.TryParse(contentType, out var mediaType))\n        return Results.BadRequest(\"Invalid Content-Type\");\n\n    var boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value;\n    if (string.IsNullOrWhiteSpace(boundary))\n        return Results.BadRequest(\"Not a multipart request\");\n\n    var reader = new MultipartReader(boundary, context.Request.Body);\n\n    \u002F\u002F CRITICAL: ReadNextSectionAsync returns null when there are no more sections\n    while (await reader.ReadNextSectionAsync() is { } section)\n    {\n        \u002F\u002F Parse Content-Disposition to identify file sections\n        if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition))\n            continue;\n\n        if (contentDisposition.DispositionType.Equals(\"form-data\")\n            && !string.IsNullOrEmpty(contentDisposition.FileName.Value))\n        {\n            \u002F\u002F Sanitize the user-provided filename to prevent path traversal\n            var originalFileName = contentDisposition.FileName.Value ?? string.Empty;\n            var sanitizedFileName = Path.GetFileName(originalFileName.Trim('\"'));\n            var safeFile = $\"{Guid.NewGuid()}\";\n\n            \u002F\u002F CRITICAL: Stream directly to disk — avoids buffering in memory\n            Directory.CreateDirectory(\"uploads\");\n            using var fileStream = File.Create(Path.Combine(\"uploads\", safeFile));\n            await section.Body.CopyToAsync(fileStream);\n        }\n    }\n\n    return Results.Ok(\"Uploaded\");\n}).DisableAntiforgery();\n\n\u002F\u002F COMMON MISTAKE: Using IFormFile for very large files\n\u002F\u002F Multipart form parsing can buffer large uploads and consume memory\u002Fdisk.\n\u002F\u002F Use MultipartReader for streaming directly to storage.\n```\n\n## Common Mistakes\n\n1. **Only configuring one size limit**: Must configure BOTH Kestrel `MaxRequestBodySize` AND `FormOptions.MultipartBodyLengthLimit`.\n2. **400 errors from anti-forgery**: In .NET 8+, `UseAntiforgery()` auto-validates form uploads. Use `.DisableAntiforgery()` for API endpoints (safe for JWT\u002Funauthenticated; do NOT disable for cookie-authenticated endpoints).\n3. **Trusting file.FileName**: User-provided filename can contain path traversal. Generate a safe filename with `Guid.NewGuid()` and derive the extension from validated content.\n4. **Trusting Content-Type only**: Content type is client-spoofable. Always check magic bytes for actual file type verification.\n5. **Using IFormFile for very large files**: Multipart form parsing buffers with a memory threshold and spills to temp files. Use `MultipartReader` to stream data in chunks directly to storage without buffering the entire file.\n6. **Deriving file extension from user input**: Prefer deriving the extension from the validated content type or magic bytes rather than `Path.GetExtension(file.FileName)`. If the original extension must be preserved, validate it against the detected content type.\n",{"name":5,"license":15,"description":7},"main","30954af1dcd1a74b63f05deb2e2c41e5ecae4a82","02-CSharp-WPF-Desktop-Development\u002Fminimal-api-file-upload","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack","https:\u002F\u002Fgithub.com\u002Fitsmejay18","2026-09-18 16:06:36",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill minimal-api-file-upload",{"tool":36,"command":37},"bunx","bunx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill minimal-api-file-upload",{"tool":39,"command":40},"pnpm","pnpm dlx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill minimal-api-file-upload","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F02-CSharp-WPF-Desktop-Development\u002Fminimal-api-file-upload\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M7D2RKBHPZ3E1RNN5DWHT550","vectorization","Design, implement, optimize, and review SIMD code in .NET. USE FOR: vectorizing scalar loops with TensorPrimitives, Vector64\u002F128\u002F256\u002F512, or platform hardware intrinsics; reviewing existing SIMD code, including Vector\u003CT>, for contract equivalence, tail handling, memory safety, portability, fallbacks, and measured performance. DO NOT USE FOR: performance work unrelated to SIMD or vectorization.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fvectorization\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7D2RDJ7RN3QK8GJR0QTER1D","resolve-project-references","Guide for interpreting ResolveProjectReferences time in MSBuild performance summaries. Activate when ResolveProjectReferences appears as the most expensive target and developers are trying to optimize it directly. Explains that the reported time includes wait time for dependent project builds and is misleading. Guides users to focus on task self-time instead. Do not activate for general build performance -- use build-perf-diagnostics instead.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fresolve-project-references\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7D2R1H2GTNZYHG9YRX3JDQW","optimizing-ef-core-queries","Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Foptimizing-ef-core-queries\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7D2QREG04W1YT0NEBHEW5C9","microbenchmarking","Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks. Also activate when microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely tool. Consider activating when answering a .NET performance question requires measurement and BenchmarkDotNet may be needed. Covers microbenchmark design, BDN configuration and project setup, how to run BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side performance comparisons. Do NOT use for profiling\u002Ftracing .NET code (dotnet-trace, PerfView), production telemetry, or load\u002Fstress testing (Crank, k6).","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fmicrobenchmarking\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7D2QGE175XWPZVACVH2868Z","incremental-build","Guide for optimizing MSBuild incremental builds. USE FOR: builds slower than expected on subsequent runs, 'nothing changed but it rebuilds anyway', diagnosing why targets re-execute unnecessarily, fixing broken no-op builds. Covers 8 common causes: missing Inputs\u002FOutputs on custom targets, volatile properties in output paths (timestamps\u002FGUIDs), file writes outside tracked Outputs, missing FileWrites registration, glob changes, Visual Studio Fast Up-to-Date Check (FUTDC) issues. Key diagnostic: look for 'Building target completely' vs 'Skipping target' in binlog. DO NOT USE FOR: first-time build slowness (use build-perf-baseline), parallelism issues (use build-parallelism), evaluation-phase slowness (use eval-performance), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fincremental-build\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7D2Q1DQTC6K49R73WQTTPSB","eval-performance","Guide for diagnosing and improving MSBuild project evaluation performance. USE FOR: builds slow before any compilation starts, high evaluation time in binlog analysis, expensive glob patterns walking large directories (node_modules, .git, bin\u002Fobj), deep import chains (>20 levels), preprocessed output >10K lines indicating heavy evaluation, property functions with file I\u002FO ($([System.IO.File]::ReadAllText(...))), multiple evaluations per project. Covers the 5 MSBuild evaluation phases, glob optimization via DefaultItemExcludes, import chain analysis with \u002Fpp preprocessing. DO NOT USE FOR: compilation-time slowness (use build-perf-diagnostics), incremental build issues (use incremental-build), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Feval-performance\u002FSKILL.md",[],[]]