为 Swagger 的 multipart/form-data 中的文件指定内容类型

Mat*_*rný 9 c# mime-types swagger asp.net-core swagger-codegen

我已经用这个签名实现了端点

[HttpPost("Test")]
public IActionResult MyTest([Required] IFormFile pdf, [Required] IFormFile image)
{
    // some stuff...

    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

这会在 swagger.json (相关部分)中生成以下条目

"content": {
    "multipart/form-data": {
        "schema": {
            "required": [
                "image",
                "pdf"
            ],
            "type": "object",
            "properties": {
                "pdf": {
                    "type": "string",
                    "format": "binary"
                },
                "image": {
                    "type": "string",
                    "format": "binary"
                }
            }
        },
        "encoding": {
            "pdf": {
                "style": "form"
            },
            "image": {
                "style": "form"
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我还需要指定编码,就像在规范(v3) 中一样。所以对于我的任务,JSON 应该是这样的,我想......

"encoding": {
    "pdf": {
        "style": "form",
        "contentType": "application/pdf"
    },
    "image": {
        "style": "form",
        "contentType": "image/png, image/jpeg"
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我怎么能从代码中做到这一点呢?我想到了SwaggerParameter 属性,但它只包含描述和必需的标志......

我在 .NET Core 2.2 上使用 Swashbuckle.AspNetCore NuGeT 包(版本 5.0.0-rc2)。

zhu*_*ber 4

如果您查看这一行,您会发现编码仅使用属性创建Style,而未ContentType设置。您可以做的是通过创建自定义内容来手动设置它,Attribute您可以在其中定义您的内容类型:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter,AllowMultiple = false)]
public class OpenApiEncodingContentTypeAttribute : Attribute
{
    public OpenApiEncodingContentTypeAttribute(string contentType)
    {
        ContentType = contentType;
    }

    public string ContentType { get; }
}
Run Code Online (Sandbox Code Playgroud)

然后Attribute在里面使用它IOperationFilter

public class FormContentTypeSchemaOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var contentTypeByParameterName = context.MethodInfo.GetParameters()
            .Where(p => p.IsDefined(typeof(OpenApiEncodingContentTypeAttribute), true))
            .ToDictionary(p => p.Name, s => s.GetCustomAttribute<OpenApiEncodingContentTypeAttribute>().ContentType);

        if (contentTypeByParameterName.Any())
        {
            foreach (var requestContent in operation.RequestBody.Content)
            {
                var encodings = requestContent.Value.Encoding;
                foreach (var encoding in encodings)
                {
                    if (contentTypeByParameterName.TryGetValue(encoding.Key, out string value))
                    {
                        encoding.Value.ContentType = value;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后用这个装饰你的参数Attribute

[HttpPost("Test")]
public IActionResult MyTest([Required] [OpenApiEncodingContentType("application/pdf")] IFormFile pdf, [Required] [OpenApiEncodingContentType("image/png, image/jpeg")] IFormFile image)
{
    // some stuff...
    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

另外不要忘记定义你IOperationFilterAddSwaggerGen

services.AddSwaggerGen(opts =>
{
    // all other stuff
    opts.OperationFilter<FormContentTypeSchemaOperationFilter>();
})
Run Code Online (Sandbox Code Playgroud)

这就是你得到的

"requestBody": {
  "content": {
    "multipart/form-data": {
      "schema": {
        "required": [
          "image",
          "pdf"
        ],
        "type": "object",
        "properties": {
          "pdf": {
            "type": "string",
            "format": "binary"
          },
          "image": {
            "type": "string",
            "format": "binary"
          }
        }
      },
      "encoding": {
        "pdf": {
          "contentType": "application/pdf",
          "style": "form"
        },
        "image": {
          "contentType": "image/png, image/jpeg",
          "style": "form"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

您可能可以IOperationFilter通过额外的检查/空检查和其他适合您需求的东西来改进,因为这只是一个基本的实现。