2016-12-14 76 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

相關問題