代码之家  ›  专栏  ›  技术社区  ›  TomSelleck

使用MemoryStream和WebAPI返回图像

  •  1
  • TomSelleck  · 技术社区  · 7 年前

    我正在尝试使端点返回包含图像的MemoryStream。

    这是迄今为止我掌握的代码:

    控制器终结点:

    [Route("v1/consumer/profile-image")]
    [HttpGet]
    public async Task<HttpResponseMessage> GetProfileImage(string id)
    {
        var result = await ImageService.GetImage(true, id);
    
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(result.BlobStream)
        };
    
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(result.ContentType);
    
        return response;
    }
    

    服务方法:

    public async Task<ImageStream> GetImage(string profileId)
    {
        var imageStream = new MemoryStream();
    
        var account = CloudStorageAccount.Parse(ConnectionString);
        var client = account.CreateCloudBlobClient();
    
        CloudBlobContainer container;
        CloudBlockBlob blob = null;
    
        container = client.GetContainerReference(ConsumerImageContainer);
        blob = container.GetBlockBlobReference(profileId);
    
        blob.FetchAttributes();
    
        blob.DownloadToStream(imageStream);
    
        return new ImageStream
        {
            BlobStream = imageStream,
            ContentType = blob.Properties.ContentType
        };
    }
    
    public class ImageStream
    {
        public MemoryStream BlobStream { get; set; }
        public string ContentType { get; set; }
    }
    

    我的问题是,我似乎没有取回任何内容-我可以看到内容类型设置正确,但图像没有:

    Request Headers
    
    Request URL: https://localhost:44347/v1/consumer/profile-image
    Request Method: GET
    Status Code: 200 
    Remote Address: [::1]:44347
    Referrer Policy: no-referrer-when-downgrade
    
    Response Headers
    
    access-control-allow-origin: *
    content-length: 0
    content-type: image/jpeg
    date: Mon, 09 Jul 2018 13:38:58 GMT
    server: Microsoft-IIS/10.0
    status: 200
    x-powered-by: ASP.NET
    x-sourcefiles: =?UTF-8?B?QzpcVXNlcnNcTWljaGFlbCBSeWFuXERvY3VtZW50c1xDb25zdW1lckFQSVxPcHRlemkuQ29uc3VtZXJBcGlcdjFcY29uc3VtZXJccHJvZmlsZS1pbWFnZQ==?=
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   TomSelleck    7 年前

    我需要在返回流位置之前重置它:

    blob.FetchAttributes();
    
    blob.DownloadToStream(imageStream);
    
    imageStream.Position = 0;
    
    return new ImageStream
    {
        BlobStream = imageStream,
        ContentType = blob.Properties.ContentType
    };