[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M756E92NJ4KZZ81QCM683EB8":3,"skill-same:01M756E92NJ4KZZ81QCM683EB8":45},{"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":29,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M756E92NJ4KZZ81QCM683EB8","minimal-api-file-upload",null,"File upload endpoints in ASP.NET minimal APIs (.NET 8+)","weiflycc-cmd\u002Fskills","weiflycc-cmd","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F250846518?v=4","01M756C4PFGZJWKK04WFB9S5XF","威飛工作室","01M756C4QJJ66QDXN2RN6SXY87",0,"MIT","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-aspnet\u002Fskills\u002Fminimal-api-file-upload\u002FSKILL.md",[],[],"2026-11-12 13:55:43",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","5810d492c9b301d8227f932bf87b5c954c4fa4d6","plugins\u002Fdotnet-aspnet\u002Fskills\u002Fminimal-api-file-upload","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd","weiflycc.com","2026-11-10 03:26:55",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add weiflycc-cmd\u002Fskills --skill minimal-api-file-upload",{"tool":37,"command":38},"bunx","bunx skills add weiflycc-cmd\u002Fskills --skill minimal-api-file-upload",{"tool":40,"command":41},"pnpm","pnpm dlx skills add weiflycc-cmd\u002Fskills --skill minimal-api-file-upload","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-aspnet\u002Fskills\u002Fminimal-api-file-upload\u002FSKILL.md",true,[],[46,53,60,67,74,81],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M76SGT4WG5682JQJ0V3NSK6X","system-text-json-net11","Provides guidance on new System.Text.Json APIs introduced in .NET 11. It covers typed JsonTypeInfo access via GetTypeInfo\u003CT> and TryGetTypeInfo\u003CT> on JsonSerializerOptions, and the new JsonNamingPolicy.PascalCase static property. Use when serializing or deserializing JSON in .NET 11 applications and needing typed metadata access or PascalCase property naming.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet11\u002Fskills\u002Fsystem-text-json-net11\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M76SGPNZYYV9BCZJW7BF7J8A","nuget-trusted-publishing","Set up NuGet trusted publishing (OIDC) on a GitHub Actions repo — replaces long-lived API keys with short-lived tokens. USE FOR: trusted publishing, NuGet OIDC, keyless NuGet publish, migrate from NuGet API key, NuGet\u002Flogin, secure NuGet publishing. DO NOT USE FOR: publishing to private feeds or Azure Artifacts (OIDC is nuget.org only). INVOKES: shell (powershell or bash), edit, create, ask_user for guided repo setup.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fnuget-trusted-publishing\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M76SGHVNBNVM1DMVDYTMAE5G","dotnet-pinvoke","Correctly call native (C\u002FC++) libraries from .NET using P\u002FInvoke and LibraryImport. Covers function signatures, string marshalling, memory lifetime, SafeHandle, and cross-platform patterns. USE FOR: writing new P\u002FInvoke or LibraryImport declarations, reviewing or debugging existing native interop code, wrapping a C or C++ library for use in .NET, diagnosing crashes, memory leaks, or corruption at the managed\u002Fnative boundary. DO NOT USE FOR: COM interop, C++\u002FCLI mixed-mode assemblies, or pure managed code with no native dependencies.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fdotnet-pinvoke\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M76SGDB9Z3GSB1CFW314NC84","csharp-scripts","Run file-based C# apps with the .NET CLI when the user explicitly wants C#\u002F.NET code without creating a project. Use for C# language\u002FAPI experiments, one-file C# apps, small multi-file C# apps composed with `#:include`\u002F`#:exclude`, or C# file-based apps linked with `#:ref`. Do not use for language-agnostic throwaway scripts, generic computations, Python\u002FPowerShell-style automation, full projects, or existing app integration.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet\u002Fskills\u002Fcsharp-scripts\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M76SG805T8W764WAKB1NP3CJ","thread-abort-migration","Guides migration of .NET Framework Thread.Abort usage to cooperative cancellation in modern .NET. USE FOR: modernizing code that calls Thread.Abort, catching ThreadAbortException, replacing Thread.ResetAbort, replacing Thread.Interrupt for thread termination, resolving PlatformNotSupportedException or SYSLIB0006 after retargeting to .NET 6+, migrating ASP.NET Response.End or Response.Redirect(url, true) which internally call Thread.Abort. DO NOT USE FOR: code that only uses Thread.Join, Thread.Sleep, or Thread.Start without any abort, interrupt, or ThreadAbortException usage — these APIs work identically in modern .NET and need no migration. Also not for projects staying on .NET Framework, or Thread.Abort usage inside third-party libraries you do not control.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fthread-abort-migration\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M76SG2588ZJBE5C51HYJJSKV","migrate-nullable-references","Enable nullable reference types in a C# project and systematically resolve all warnings. USE FOR: adopting NRTs in existing codebases, file-by-file or project-wide migration, fixing CS8602\u002FCS8618\u002FCS86xx warnings, annotating APIs for nullability, cleaning up null-forgiving operators, upgrading dependencies with new nullable annotations. DO NOT USE FOR: projects already fully migrated with zero warnings (unless auditing suppressions), fixing a handful of nullable warnings in code that already has NRTs enabled, suppressing warnings without fixing them, C# 7.3 or earlier projects. INVOKES: Get-NullableReadiness.ps1 scanner script.","https:\u002F\u002Fgithub.com\u002Fweiflycc-cmd\u002Fskills\u002Fblob\u002Fmain\u002Fplugins\u002Fdotnet-upgrade\u002Fskills\u002Fmigrate-nullable-references\u002FSKILL.md",[],[]]