使用SwashBuckle返回文件流

时间:2018-05-10 10:47:11

标签: c# stream swagger swashbuckle

我想使用SwashBuckle

返回文件流
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("Files/{uid}/file")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(Byte[]))]
    public HttpResponseMessage DownloadFile(String uid, String fileName)
    {
        return Safe.Execute(() =>
        {
            var api = new FileApi();
            var stream = api.GetFile(uid, fileName);

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition =
                     new ContentDispositionHeaderValue("attachment")
                     {
                         FileName = CalcFileName(fileName)
                     };
            return result;
        });
    }

我看到该文件被返回,但......不知怎的......编码。通过UI下载后,3798长文件变为5789字节,文件内容与预期非常相似,但包含额外字节,就像它被解释为String并成为UTF-8编码版本一样。

当我将其替换为:

时,没有任何变化
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(Stream))]

Swagger生成的desciptor看起来像:

        "produces": [    
          "application/json",    
          "text/json",    
          "application/xml",    
          "text/xml"    
        ],    
        ...
        "responses": {    
          "200": {    
            "description": "OK",    
            "schema": {    
              "format": "byte",    
              "type": "string"
        }

知道如何实现从控制器方法返回文件流吗?

1 个答案:

答案 0 :(得分:1)

要描述API方法,您可以在swagger配置中使用IOperationFilter

public class UpdateFileDownloadOperations : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry s, ApiDescription a)
    {
        if (operation.operationId == "DownloadFile_Get")
        {
            operation.produces = new[] { "application/octet-stream" };
        }
    }
}

如果您从未使用过滤器,请查看项目的页面: https://github.com/domaindrivendev/Swashbuckle/blob/e0053e1864defa3c4f73ca2a960eb876e257cc9e/Swashbuckle.Dummy.Core/App_Start/SwaggerConfig.cs


在我的评论示例中,我使用Swagger-Net非常相似,但我做了一些改进,可能您注意到它使用了最新的Swagger-UI