将CryptoStream与StreamContent一起使用c#

时间:2016-11-23 16:00:35

标签: c# asp.net-web-api cryptostream

我想从文件或blob存储中读取图像,base64将其编码为流,然后将该流传递给StreamContent。以下代码超时:

[HttpGet, Route("{id}", Name = "GetImage")]
public HttpResponseMessage GetImage([FromUri] ImageRequest request)
{
   var filePath = HostingEnvironment.MapPath("~/Areas/API/Images/Mr-Bean-Drivers-License.jpg");
   HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
   var stream = new FileStream(filePath, FileMode.Open);
   var cryptoStream = new CryptoStream(stream, new ToBase64Transform(), CryptoStreamMode.Write);
   result.Content = new StreamContent(cryptoStream);
   result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

   return result;
}

我能够在不将文件保存为流的情况下使用以下代码,并将其全部读入内存,但我想避免这种情况。

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
    using (var image = Image.FromStream(fileStream))
    {
        var memoryStream = new MemoryStream();
        image.Save(memoryStream, image.RawFormat);

        byte[] imageBytes = memoryStream.ToArray();

        var base64String = Convert.ToBase64String(imageBytes);
        result.Content = new StringContent(base64String);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
        return result;
    }
}

1 个答案:

答案 0 :(得分:2)

这里的问题是您要将CryptoStreamMode.Write传递给CryptoStream的构造函数,而您应该传递CryptoStreamMode.Read,因为CryptoStream将被读为{ {1}}返回。

有关此的更多详细信息,请参见Figolu对this answerHttpResponseMessage的各种用法的详尽解释。