2016-12-14 71 views
2

我有一个接受的二进制软件包和地方存储他们的WebAPI控制器。由于这些包可能会变得很大,我不想通过添加一个字节数组参数将它们加载到内存中,而是传递一个流。我怎么能告诉Swashbuckle的主体内容是必需的?

我找到了一种方法来做到这一点in this answer

[HttpPost] 
[Route("Store/{projectId}")] 
public async Task Store(string projectId) 
{ 
    using (var stream = await this.Request.Content.ReadAsStreamAsync()) 
    { 
     await this.packageManager.StorePackageAsync(projectId, stream); 
    } 
} 

这工作,我可以将文件发送到使用邮差控制器。但是,我现在想用Swashbuckle生成Swagger文档,当然,在那里没有提到所需的主体内容。

是否有一种方式来获得请求的内容流,这样Swashbuckle知道吗?还是有一个属性可以用来告诉它所需的内容?

回答

3

要做到这一点,你必须做两件事情。

首先,你必须告诉扬鞭有在包含二进制数据的身体参数。接下来,你必须告诉Swagger终点消耗二进制数据(例如application/octet-stream)。

Swashbuckle不支持此开箱。但是您可以创建自定义过滤器来扩展Swashbuckle的功能。我通常做的是创建一个自定义属性来装饰一个方法,然后创建一个自定义过滤器来对该属性进行操作。

你的情况,这会做的伎俩:

自定义属性

public class BinaryPayloadAttribute : Attribute 
{ 
    public BinaryPayloadAttribute() 
    { 
     ParameterName = "payload"; 
     Required = true; 
     MediaType = "application/octet-stream"; 
     Format = "binary"; 
    } 

    public string Format { get; set; } 

    public string MediaType { get; set; } 

    public bool Required { get; set; } 

    public string ParameterName { get; set; } 
} 

的自定义过滤器

public class BinaryPayloadFilter : IOperationFilter 
{ 
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) 
    { 
     var attribute = apiDescription.GetControllerAndActionAttributes<BinaryPayloadAttribute>().FirstOrDefault(); 
     if (attribute == null) 
     { 
      return; 
     } 

     operation.consumes.Clear(); 
     operation.consumes.Add(attribute.MediaType); 

     operation.parameters.Add(new Parameter 
     { 
      name = attribute.ParameterName, 
      @in = "body", 
      required = attribute.Required, 
      type = "string", 
      format = attribute.Format 
     }); 
    } 
} 

过滤器添加到Swashbuckle配置

GlobalConfiguration.Configuration 
    .EnableSwagger(c => 
     { 
      // other configuration setting removed for brevity 
      c.OperationFilter<BinaryPayloadFilter>(); 
     }); 

应用属性的方法

[HttpPost] 
[BinaryPayload] 
[Route("Store/{projectId}")] 
public async Task Store(string projectId) 
{ 
    ... 
} 

在扬鞭UI你再得到:

Swagger UI

相关问题