2017-02-24 63 views
0

我正在實現一個現有的Web API的Swagger接口。當前的API控制器公開了異步上傳功能,該功能使用Request.Content來異步傳輸圖像。在this文章中解釋了已使用的代碼。API文件上傳使用HTTP內容沒有暴露在sw 012中

我的API控制器:

[HttpPost] 
    [Route("foo/bar/upload")] 
    public async Task<HttpResponseMessage> Upload() 
    { 
     if (!Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 
     var provider = await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider()); 
     NameValueCollection formData = provider.FormData; 
     HttpResponseMessage response; 
     //access files 
     IList<HttpContent> files = provider.Files; 
     if (files.Count > 0) 
     { 
      HttpContent file1 = files[0]; 
      using (Stream input = await file1.ReadAsStreamAsync()) 
      { 
       object responseObj = ExternalProcessInputStream(input) 
       response = Request.CreateResponse(HttpStatusCode.OK, responseObj); 
      } 
     } 
     else 
     { 
      response = Request.CreateResponse(HttpStatusCode.BadRequest); 
     } 
     return response; 
    } 

這工作花花公子,但是當我通過招搖公開此我有一個參數的函數,使用時將返回錯誤。

我的問題是如何提供一個合適的值來測試這種方法?

回答

2

您需要添加一個自定義IOperationFilter來處理這個問題。

假設你有一個控制器,像這樣:

[ValidateMimeMultipartContentFilter] 
    [HttpPost, Route("softwarepackage")] 
    public Task<SoftwarePackageModel> UploadSingleFile() 
    { 

     var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder); 
     var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<SoftwarePackageModel>(t => 
     { 
      var firstFile = streamProvider.FileData.FirstOrDefault(); 

      if (firstFile != null) 
      { 
       // Do something with firstFile.LocalFileName 
      } 

      return new SoftwarePackageModel 
      { 

      }; 
     }); 

     return task; 
    } 

然後,您需要創建一個Swashbuckle.Swagger.IOperationFilter將文件上載參數添加到您的功能,如:

​​

而且在你需要註冊過濾器的Swagger配置:

config.EnableSwagger(c => {... c.OperationFilter<FileOperationFilter>(); ... }); 

爲了達到這個目的,I als o添加FilterAttribute以過濾出多部分內容:

public class ValidateMimeMultipartContentFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     if (!actionContext.Request.Content.IsMimeMultipartContent()) 
     { 
      throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 
     } 
    } 

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) 
    { 

    } 

} 
+0

該過濾器是一個很好的補充。 – martijn