You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swashbuckle.AspNetCore升级后如何定义File Schema Type?

解决Swashbuckle.AspNetCore v6.5.0中文件返回类型的定义问题

Swashbuckle.AspNetCore从v5版本开始全面切换到OpenAPI v3规范,原来的Response.Schema属性已被移除,取而代之的是基于Content媒体类型的结构。要正确定义文件类型的响应,需要按OpenAPI v3的规范修改代码:

正确的FileSchemaType实现

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

public class FileSchemaType : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var targetOperationIds = new[] { "ExportToExcel", "ExportToPdf", "GetReport", "DownloadFile" };
        if (!targetOperationIds.Contains(operation.OperationId))
            return;

        // 清空原有响应内容,避免格式冲突
        operation.Responses["200"].Content.Clear();

        // 通用二进制文件配置(适配任意下载场景)
        operation.Responses["200"].Content.Add("application/octet-stream", new OpenApiMediaType
        {
            Schema = new OpenApiSchema
            {
                Type = "string",
                Format = "binary"
            }
        });

        // 可根据实际文件类型补充对应Content-Type,示例:
        // Excel文件
        // operation.Responses["200"].Content.Add("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", new OpenApiMediaType
        // {
        //     Schema = new OpenApiSchema { Type = "string", Format = "binary" }
        // });

        // PDF文件
        // operation.Responses["200"].Content.Add("application/pdf", new OpenApiMediaType
        // {
        //     Schema = new OpenApiSchema { Type = "string", Format = "binary" }
        // });
    }
}

关键改动说明

  1. 替换Schema为Content结构:OpenAPI v3要求通过Content字典定义响应体,键为具体的Content-Type,值包含对应的Schema信息
  2. 文件类型的标准定义:OpenAPI v3中用Type = "string" + Format = "binary"表示二进制文件,对应旧版本的Type = "file"
  3. 精准适配文件类型:可根据接口实际返回的文件类型(Excel、PDF等)添加对应的媒体类型,让Swagger UI更精准展示下载选项

注册过滤器

确保在Swagger配置中注册该过滤器:

services.AddSwaggerGen(options =>
{
    // 其他Swagger配置项...
    options.OperationFilters.Add<FileSchemaType>();
});

内容的提问来源于stack exchange,提问作者Mustafa Alamir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 00:32:34