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

时间:2019-06-17 16:22:28

标签: c# asp.net-core swagger mime-types swagger-codegen

我已经使用此签名实现了端点

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

    return Ok();
}

这会在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"
            }
        }
    }
}

但是,我还需要指定编码,例如the specs(v3)。所以对于我的任务,我认为JSON应该看起来像这样……

"encoding": {
    "pdf": {
        "style": "form",
        "contentType": "application/pdf"
    },
    "image": {
        "style": "form",
        "contentType": "image/png, image/jpeg"
    }
}

但是我该如何从代码中做到这一点?我想到了SwaggerParameter attribute,但是它只包含描述和必需的标志...

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

2 个答案:

答案 0 :(得分:2)

如果您查看this line,则会看到仅使用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; }
}

,然后在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;
                    }
                }
            }
        }
    }
}

然后只需使用此Attribute

装饰参数
[HttpPost("Test")]
public IActionResult MyTest([Required] [OpenApiEncodingContentType("application/pdf")] IFormFile pdf, [Required] [OpenApiEncodingContentType("image/png, image/jpeg")] IFormFile image)
{
    // some stuff...
    return Ok();
}

也不要忘记在IOperationFilter中定义AddSwaggerGen

services.AddSwaggerGen(opts =>
{
    // all other stuff
    opts.OperationFilter<FormContentTypeSchemaOperationFilter>();
})

这就是你得到的

"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"
        }
      }
    }
  }
}

您可能可以通过附加检查/空检查和其他适合您需要的内容来改善IOperationFilter,因为这只是一个基本实现。

答案 1 :(得分:0)

您还可以查看ISchemaFilter和以下问题:

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1148

这可能有助于您过滤操作并为同一类型(IFormInput)添加不同的contentStyles。

我相信您当前要实现的目标只有使用自定义属性,但是在活动开发中有一个活动的分支可增强FormsInput支持,也许您可​​以添加功能请求。

https://github.com/domaindrivendev/Swashbuckle.AspNetCore/commits/enhance-support-for-forms