Token导航 LogoToken导航

Agent Skill · 前端设计

file-handling(文件处理)

file-handling 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

file-handling 是前端设计类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为调用外部服务;许可证信息还不明确,第三方扫描已通过,按安装量在前端设计类的 10,216 个 Skill 里排第 7,903。

总安装 329周安装 14GitHub Stars 16下载 115核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:file-handling(文件处理)
来源仓库:https://github.com/wshaddix/dotnet-skills
仓库路径:skills/file-handling
安装命令:
npx skills add https://github.com/wshaddix/dotnet-skills --skill file-handling
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/wshaddix/dotnet-skills --skill file-handling

这个 Skill 是做什么的

前端设计类 Skill 关注页面结构、视觉规范和组件写法,输出通常是可运行的界面代码。

file-handling 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息。适合在 Codex、Claude、Cursor、Gemini CLI 中围绕仓库状态或协作事项进行整理。通过 npx skills add 命令从指定仓库安装并使用。

建议确认权限范围和维护状态,注意是否触发联网或文件读写操作。可结合原始 README 进一步核验具体用法和功能边界。

来源仓库内路径:skills/file-handling

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/wshaddix/dotnet-skills --skill file-handling;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要调用外部服务,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

file-handling 怎么安装?

在终端执行 npx skills add https://github.com/wshaddix/dotnet-skills --skill file-handling。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

file-handling 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

file-handling 需要什么权限?

权限级别是调用外部服务。该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

file-handling 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

file-handling 用的人多吗?

公开数据是累计安装 329 次,近一周安装 14 次,下载 115 次,GitHub 16 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

file-handling 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理前端设计类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

前端设计类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
frontend-design

前端设计 · Codex、Claude

8,823,360126,072只读MIT通过
vercel-composition-patterns

Vercel 组合模式 · Codex、Claude

3,858,81625,893需要联网MIT通过
vercel-react-native-skills

Vercel React native skills 前端 · Codex、Claude

2,468,66425,878只读MIT通过
adapt

adapt 搜索 · Codex、Claude

2,027,04023,125操作浏览器未明确通过
bolder

bolder 分析 · Codex、Claude

2,004,28823,130只读未明确通过
file-handling

文件处理 · 本页

32916调用外部服务未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Rationale

File handling is a common requirement but presents significant security and scalability challenges. Improper implementation can lead to security vulnerabilities (path traversal, malicious uploads), memory exhaustion, and storage inefficiencies. These patterns provide secure, performant, and maintainable approaches to file operations in Razor Pages.

Patterns

Pattern 1: Secure File Upload Validation

Implement comprehensive validation for file uploads including type, size, and content verification.

public class FileUploadValidator
{
    private readonly long _maxFileSize;
    private readonly string[] _allowedExtensions;
    private readonly Dictionary<string, byte[]> _fileSignatures;

    public FileUploadValidator(IConfiguration configuration)
    {
        _maxFileSize = configuration.GetValue<long>("FileUpload:MaxSize", 10 * 1024 * 1024); // 10MB
        _allowedExtensions = configuration.GetSection("FileUpload:AllowedExtensions")
            .Get<string[]>() ?? new[] { ".jpg", ".jpeg", ".png", ".pdf", ".doc", ".docx" };

        // Magic numbers for file type validation
        _fileSignatures = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase)
        {
            [".jpg"] = new byte[] { 0xFF, 0xD8, 0xFF },
            [".jpeg"] = new byte[] { 0xFF, 0xD8, 0xFF },
            [".png"] = new byte[] { 0x89, 0x50, 0x4E, 0x47 },
            [".pdf"] = new byte[] { 0x25, 0x50, 0x44, 0x46 },
            [".docx"] = new byte[] { 0x50, 0x4B, 0x03, 0x04 }
        };
    }

    public async Task<ValidationResult> ValidateAsync(IFormFile file)
    {
        // Check file exists
        if (file == null || file.Length == 0)
        {
            return ValidationResult.Failure("No file provided");
        }

        // Check file size
        if (file.Length > _maxFileSize)
        {
            return ValidationResult.Failure(
                $"File size exceeds maximum allowed size of {_maxFileSize / 1024 / 1024}MB");
        }

        // Get and validate extension
        var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
        if (!_allowedExtensions.Contains(extension))
        {
            return ValidationResult.Failure(
                $"File type '{extension}' is not allowed. Allowed types: {string.Join(", ", _allowedExtensions)}");
        }

        // Validate file signature (magic number)
        if (_fileSignatures.TryGetValue(extension, out var signature))
        {
            using var stream = file.OpenReadStream();
            var header = new byte[signature.Length];
            var bytesRead = await stream.ReadAsync(header, 0, signature.Length);

            if (bytesRead < signature.Length || !header.SequenceEqual(signature))
            {
                return ValidationResult.Failure(
                    "File content does not match the declared file type");
            }
        }

        // Reset stream position if needed later
        if (file is { Position: > 0 })
        {
            file.Position = 0;
        }

        return ValidationResult.Success();
    }
}

public record ValidationResult(bool IsValid, string? ErrorMessage)
{
    public static ValidationResult Success() => new(true, null);
    public static ValidationResult Failure(string error) => new(false, error);
}

Pattern 2: Streaming Large Files

Handle large file uploads efficiently without loading entire files into memory.

public class StreamingFileUploadModel : PageModel
{
    private readonly IFileStorageService _storage;
    private readonly FileUploadValidator _validator;
    private readonly ILogger<StreamingFileUploadModel> _logger;

    public StreamingFileUploadModel(
        IFileStorageService storage,
        FileUploadValidator validator,
        ILogger<StreamingFileUploadModel> logger)
    {
        _storage = storage;
        _validator = validator;
        _logger = logger;
    }

    [BindProperty]
    public string? Description { get; set; }

    public string? ErrorMessage { get; set; }
    public string? SuccessMessage { get; set; }

    // Disable form value limit for streaming
    [RequestSizeLimit(500 * 1024 * 1024)] // 500MB
    [RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = 500 * 1024 * 1024)]
    public async Task<IActionResult> OnPostAsync()
    {
        if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
        {
            ErrorMessage = "Invalid content type";
            return Page();
        }

        var boundary = MultipartRequestHelper.GetBoundary(
            MediaTypeHeaderValue.Parse(Request.ContentType),
            int.MaxValue);

        var reader = new MultipartReader(boundary, HttpContext.Request.Body);
        var section = await reader.ReadNextSectionAsync();

        while (section != null)
        {
            if (ContentDispositionHeaderValue.TryParse(
                section.ContentDisposition, out var contentDisposition))
            {
                if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                {
                    var fileName = contentDisposition.FileName.Value?.Trim('"') ?? "unnamed";
                    var safeFileName = Path.GetFileName(fileName); // Prevent path traversal

                    // Validate file type by extension
                    var extension = Path.GetExtension(safeFileName).ToLowerInvariant();
                    var allowedExtensions = new[] { ".pdf", ".doc", ".docx" };

                    if (!allowedExtensions.Contains(extension))
                    {
                        ErrorMessage = $"File type '{extension}' not allowed";
                        return Page();
                    }

                    // Stream directly to storage without loading into memory
                    var fileId = await _storage.UploadStreamAsync(
                        section.Body,
                        safeFileName,
                        section.ContentType ?? "application/octet-stream");

                    SuccessMessage = $"File uploaded successfully with ID: {fileId}";

                    // Log upload
                    _logger.LogInformation(
                        "File uploaded: {FileName} with ID {FileId} by user {User}",
                        safeFileName, fileId, User.Identity?.Name ?? "anonymous");
                }
            }

            section = await reader.ReadNextSectionAsync();
        }

        return Page();
    }
}

// Helper class
public static class MultipartRequestHelper
{
    public static string GetBoundary(MediaTypeHeaderValue contentType, int lengthLimit)
    {
        var boundary = HeaderUtilities.RemoveQuotes(contentType.Boundary).Value;

        if (string.IsNullOrWhiteSpace(boundary))
        {
            throw new InvalidDataException("Missing content-type boundary");
        }

        if (boundary.Length > lengthLimit)
        {
            throw new InvalidDataException(
                $"Multipart boundary length limit {lengthLimit} exceeded");
        }

        return boundary;
    }

    public static bool IsMultipartContentType(string? contentType) =>
        !string.IsNullOrEmpty(contentType) &&
        contentType.Contains("multipart/", StringComparison.OrdinalIgnoreCase);

    public static bool HasFormDataContentDisposition(ContentDispositionHeaderValue contentDisposition) =>
        contentDisposition != null &&
        contentDisposition.DispositionType.Equals("form-data") &&
        string.IsNullOrEmpty(contentDisposition.FileName.Value) &&
        string.IsNullOrEmpty(contentDisposition.FileNameStar.Value);

    public static bool HasFileContentDisposition(ContentDispositionHeaderValue contentDisposition) =>
        contentDisposition != null &&
        contentDisposition.DispositionType.Equals("form-data") &&
        (!string.IsNullOrEmpty(contentDisposition.FileName.Value) ||
         !string.IsNullOrEmpty(contentDisposition.FileNameStar.Value));
}

Pattern 3: Storage Abstraction

Abstract storage implementation to support multiple backends (local, Azure Blob, S3).

// Storage abstraction interface
public interface IFileStorageService
{
    Task<string> UploadAsync(IFormFile file, CancellationToken ct = default);
    Task<string> UploadStreamAsync(Stream stream, string fileName, string contentType, CancellationToken ct = default);
    Task<Stream?> DownloadAsync(string fileId, CancellationToken ct = default);
    Task DeleteAsync(string fileId, CancellationToken ct = default);
    Task<FileMetadata?> GetMetadataAsync(string fileId, CancellationToken ct = default);
    Task<bool> ExistsAsync(string fileId, CancellationToken ct = default);
}

public record FileMetadata(
    string FileId,
    string FileName,
    string ContentType,
    long Size,
    DateTimeOffset UploadedAt,
    string UploadedBy);

// Local file system implementation
public class LocalFileStorageService : IFileStorageService
{
    private readonly string _basePath;
    private readonly ILogger<LocalFileStorageService> _logger;

    public LocalFileStorageService(IConfiguration configuration, ILogger<LocalFileStorageService> logger)
    {
        _basePath = configuration.GetValue<string>("Storage:LocalPath") ?? "uploads";
        _logger = logger;

        // Ensure directory exists
        Directory.CreateDirectory(_basePath);
    }

    public async Task<string> UploadAsync(IFormFile file, CancellationToken ct = default)
    {
        var fileId = Guid.NewGuid().ToString("N");
        var safeFileName = Path.GetFileName(file.FileName);
        var extension = Path.GetExtension(safeFileName);
        var storageFileName = $"{fileId}{extension}";

        var filePath = Path.Combine(_basePath, storageFileName);

        using var stream = File.Create(filePath);
        await file.CopyToAsync(stream, ct);

        _logger.LogInformation("File uploaded: {FileId} ({FileName})", fileId, safeFileName);

        return fileId;
    }

    public async Task<string> UploadStreamAsync(Stream stream, string fileName, string contentType, CancellationToken ct = default)
    {
        var fileId = Guid.NewGuid().ToString("N");
        var extension = Path.GetExtension(fileName);
        var storageFileName = $"{fileId}{extension}";

        var filePath = Path.Combine(_basePath, storageFileName);

        using var fileStream = File.Create(filePath);
        await stream.CopyToAsync(fileStream, ct);

        return fileId;
    }

    public Task<Stream?> DownloadAsync(string fileId, CancellationToken ct = default)
    {
        var filePath = FindFilePath(fileId);

        if (filePath == null)
        {
            return Task.FromResult<Stream?>(null);
        }

        return Task.FromResult<Stream?>(File.OpenRead(filePath));
    }

    public Task DeleteAsync(string fileId, CancellationToken ct = default)
    {
        var filePath = FindFilePath(fileId);

        if (filePath != null)
        {
            File.Delete(filePath);
            _logger.LogInformation("File deleted: {FileId}", fileId);
        }

        return Task.CompletedTask;
    }

    public Task<FileMetadata?> GetMetadataAsync(string fileId, CancellationToken ct = default)
    {
        var filePath = FindFilePath(fileId);

        if (filePath == null)
        {
            return Task.FromResult<FileMetadata?>(null);
        }

        var fileInfo = new FileInfo(filePath);
        var metadata = new FileMetadata(
            fileId,
            fileInfo.Name,
            MimeTypes.GetMimeType(fileInfo.Extension),
            fileInfo.Length,
            fileInfo.CreationTimeUtc,
            "unknown");

        return Task.FromResult<FileMetadata?>(metadata);
    }

    public Task<bool> ExistsAsync(string fileId, CancellationToken ct = default)
    {
        return Task.FromResult(FindFilePath(fileId) != null);
    }

    private string? FindFilePath(string fileId)
    {
        var files = Directory.GetFiles(_basePath, $"{fileId}.*");
        return files.FirstOrDefault();
    }
}

// Azure Blob Storage implementation
public class AzureBlobStorageService : IFileStorageService
{
    private readonly BlobContainerClient _containerClient;
    private readonly ILogger<AzureBlobStorageService> _logger;

    public AzureBlobStorageService(IConfiguration configuration, ILogger<AzureBlobStorageService> logger)
    {
        var connectionString = configuration.GetConnectionString("AzureStorage");
        var containerName = configuration.GetValue<string>("Storage:ContainerName") ?? "uploads";

        _containerClient = new BlobContainerClient(connectionString, containerName);
        _containerClient.CreateIfNotExists();
        _logger = logger;
    }

    public async Task<string> UploadAsync(IFormFile file, CancellationToken ct = default)
    {
        var fileId = Guid.NewGuid().ToString("N");
        var blobClient = _containerClient.GetBlobClient(fileId);

        using var stream = file.OpenReadStream();
        await blobClient.UploadAsync(stream, new BlobHttpHeaders
        {
            ContentType = file.ContentType,
            ContentDisposition = $"attachment; filename=\"{file.FileName}\""
        }, cancellationToken: ct);

        return fileId;
    }

    public async Task<string> UploadStreamAsync(Stream stream, string fileName, string contentType, CancellationToken ct = default)
    {
        var fileId = Guid.NewGuid().ToString("N");
        var blobClient = _containerClient.GetBlobClient(fileId);

        await blobClient.UploadAsync(stream, new BlobHttpHeaders
        {
            ContentType = contentType,
            ContentDisposition = $"attachment; filename=\"{fileName}\""
        }, cancellationToken: ct);

        return fileId;
    }

    public async Task<Stream?> DownloadAsync(string fileId, CancellationToken ct = default)
    {
        var blobClient = _containerClient.GetBlobClient(fileId);

        if (!await blobClient.ExistsAsync(ct))
        {
            return null;
        }

        var response = await blobClient.DownloadAsync(ct);
        return response.Value.Content;
    }

    public async Task DeleteAsync(string fileId, CancellationToken ct = default)
    {
        var blobClient = _containerClient.GetBlobClient(fileId);
        await blobClient.DeleteIfExistsAsync(cancellationToken: ct);
    }

    public async Task<FileMetadata?> GetMetadataAsync(string fileId, CancellationToken ct = default)
    {
        var blobClient = _containerClient.GetBlobClient(fileId);

        if (!await blobClient.ExistsAsync(ct))
        {
            return null;
        }

        var properties = await blobClient.GetPropertiesAsync(cancellationToken: ct);

        return new FileMetadata(
            fileId,
            properties.Value.Metadata.GetValueOrDefault("originalFileName", fileId),
            properties.Value.ContentType,
            properties.Value.ContentLength,
            properties.Value.CreatedOn,
            properties.Value.Metadata.GetValueOrDefault("uploadedBy", "unknown"));
    }

    public async Task<bool> ExistsAsync(string fileId, CancellationToken ct = default)
    {
        var blobClient = _containerClient.GetBlobClient(fileId);
        return await blobClient.ExistsAsync(ct);
    }
}

Pattern 4: File Download with Security

Secure file downloads with proper content disposition and authorization.

public class FileDownloadModel : PageModel
{
    private readonly IFileStorageService _storage;
    private readonly ILogger<FileDownloadModel> _logger;

    public FileDownloadModel(IFileStorageService storage, ILogger<FileDownloadModel> logger)
    {
        _storage = storage;
        _logger = logger;
    }

    public async Task<IActionResult> OnGetAsync(string id)
    {
        // Validate file ID format
        if (!Guid.TryParseExact(id, "N", out _))
        {
            return BadRequest("Invalid file ID");
        }

        // Get metadata
        var metadata = await _storage.GetMetadataAsync(id);
        if (metadata == null)
        {
            return NotFound();
        }

        // Check authorization
        if (!await AuthorizeDownloadAsync(metadata))
        {
            _logger.LogWarning(
                "Unauthorized download attempt for file {FileId} by user {User}",
                id, User.Identity?.Name);
            return Forbid();
        }

        // Get file stream
        var stream = await _storage.DownloadAsync(id);
        if (stream == null)
        {
            return NotFound();
        }

        // Log access
        _logger.LogInformation(
            "File downloaded: {FileId} ({FileName}) by user {User}",
            id, metadata.FileName, User.Identity?.Name);

        // Return file with proper headers
        return File(stream, metadata.ContentType, metadata.FileName);
    }

    private Task<bool> AuthorizeDownloadAsync(FileMetadata metadata)
    {
        // Implement your authorization logic
        // Example: Check if user owns the file, has specific role, etc.
        return Task.FromResult(User.Identity?.IsAuthenticated == true);
    }
}

// View with secure download link
// <a asp-page="/Files/Download" asp-route-id="@Model.FileId" class="btn btn-primary">
//     Download
// </a>

Pattern 5: Image Processing and Optimization

Handle image uploads with resizing and format optimization.

public class ImageProcessingService
{
    private readonly IFileStorageService _storage;
    private readonly ILogger<ImageProcessingService> _logger;

    public ImageProcessingService(IFileStorageService storage, ILogger<ImageProcessingService> logger)
    {
        _storage = storage;
        _logger = logger;
    }

    public async Task<ImageUploadResult> ProcessAndUploadAsync(
        IFormFile file,
        ImageProcessingOptions options,
        CancellationToken ct = default)
    {
        using var image = await Image.LoadAsync(file.OpenReadStream(), ct);

        // Resize if needed
        if (options.MaxWidth > 0 && image.Width > options.MaxWidth)
        {
            image.Mutate(x => x.Resize(options.MaxWidth, 0));
        }

        if (options.MaxHeight > 0 && image.Height > options.MaxHeight)
        {
            image.Mutate(x => x.Resize(0, options.MaxHeight));
        }

        // Optimize quality
        var encoder = GetEncoder(options.Format, options.Quality);

        using var outputStream = new MemoryStream();
        await image.SaveAsync(outputStream, encoder, ct);
        outputStream.Position = 0;

        var fileId = await _storage.UploadStreamAsync(
            outputStream,
            file.FileName,
            GetContentType(options.Format),
            ct);

        return new ImageUploadResult(
            fileId,
            image.Width,
            image.Height,
            outputStream.Length);
    }

    private IImageEncoder GetEncoder(ImageFormat format, int quality)
    {
        return format switch
        {
            ImageFormat.Jpeg => new JpegEncoder { Quality = quality },
            ImageFormat.Png => new PngEncoder(),
            ImageFormat.Webp => new WebpEncoder { Quality = quality },
            _ => new JpegEncoder { Quality = quality }
        };
    }

    private static string GetContentType(ImageFormat format) => format switch
    {
        ImageFormat.Jpeg => "image/jpeg",
        ImageFormat.Png => "image/png",
        ImageFormat.Webp => "image/webp",
        _ => "image/jpeg"
    };
}

public record ImageUploadResult(
    string FileId,
    int Width,
    int Height,
    long FileSize);

public class ImageProcessingOptions
{
    public int MaxWidth { get; set; }
    public int MaxHeight { get; set; }
    public int Quality { get; set; } = 85;
    public ImageFormat Format { get; set; } = ImageFormat.Jpeg;
}

public enum ImageFormat
{
    Jpeg,
    Png,
    Webp
}

Anti-Patterns

// ❌ BAD: Trusting file extension for validation
var extension = Path.GetExtension(file.FileName);
if (extension == ".jpg") // Only checks extension!
{
    // Malicious file could have .jpg extension but be executable
}

// ✅ GOOD: Validate file signature (magic numbers)
if (!await ValidateFileSignatureAsync(file))
{
    return ValidationResult.Failure("Invalid file content");
}

// ❌ BAD: Loading entire file into memory
using var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
var bytes = memoryStream.ToArray(); // Memory explosion for large files!

// ✅ GOOD: Stream directly to storage
await _storage.UploadStreamAsync(file.OpenReadStream(), fileName, contentType);

// ❌ BAD: Using original file name for storage
var fileName = file.FileName; // Could be "../../../etc/passwd"
var path = Path.Combine(uploadsFolder, fileName);
await file.CopyToAsync(new FileStream(path, FileMode.Create));

// ✅ GOOD: Generate safe file name
var safeFileName = Path.GetFileName(file.FileName); // Removes path
var fileId = Guid.NewGuid().ToString("N");
var storagePath = Path.Combine(uploadsFolder, $"{fileId}{Path.GetExtension(safeFileName)}");

// ❌ BAD: No size limits
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
    // Accepts files of any size - can crash the server!
}

// ✅ GOOD: Enforce size limits
[RequestSizeLimit(100 * 1024 * 1024)] // 100MB
[RequestFormLimits(MultipartBodyLengthLimit = 100 * 1024 * 1024)]
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
    if (file.Length > 10 * 1024 * 1024) // 10MB per file
    {
        return BadRequest("File too large");
    }
}

// ❌ BAD: Synchronous file operations
public IActionResult OnPost(IFormFile file)
{
    file.CopyTo(stream); // Blocking call!
}

// ✅ GOOD: Async operations
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
    await file.CopyToAsync(stream);
}

// ❌ BAD: No cleanup on failure
public async Task<string> UploadAsync(IFormFile file)
{
    var tempPath = Path.GetTempFileName();
    await file.CopyToAsync(System.IO.File.Create(tempPath));

    // If upload fails, temp file is never cleaned up!
    var result = await UploadToCloudAsync(tempPath);
    return result;
}

// ✅ GOOD: Proper cleanup
public async Task<string> UploadAsync(IFormFile file)
{
    var tempPath = Path.GetTempFileName();
    try
    {
        await using var stream = System.IO.File.Create(tempPath);
        await file.CopyToAsync(stream);
        return await UploadToCloudAsync(tempPath);
    }
    finally
    {
        if (System.IO.File.Exists(tempPath))
        {
            System.IO.File.Delete(tempPath);
        }
    }
}

// ❌ BAD: Exposing internal file paths
return Ok(new { FilePath = "/var/www/uploads/abc123.pdf" });

// ✅ GOOD: Use opaque identifiers
return Ok(new { FileId = "abc123", DownloadUrl = "/files/download/abc123" });

// ❌ BAD: No virus scanning
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
    await _storage.UploadAsync(file); // Could upload malware!
}

// ✅ GOOD: Scan files before storage
public async Task<IActionResult> OnPostAsync(IFormFile file)
{
    var scanResult = await _virusScanner.ScanAsync(file);
    if (!scanResult.IsClean)
    {
        _logger.LogWarning("Malicious file upload attempted: {Threats}", scanResult.Threats);
        return BadRequest("File failed security scan");
    }

    await _storage.UploadAsync(file);
}

References

平台分布

Codex

35.47%
按下载量换算41

Claude

28.63%
按下载量换算33

Cursor

21.7%
按下载量换算25

Gemini CLI

9.07%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

调用外部服务

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills