【发布时间】:2017-09-21 10:44:16
【问题描述】:
我有一个用于存储图像的 Azure blob 容器。我还有一套 ASP.NET Web API 方法,用于添加/删除/列出此容器中的 blob。如果我将图像作为文件上传,这一切都有效。但我现在想将图像作为流上传,但出现错误。
public async Task<HttpResponseMessage> AddImageStream(Stream filestream, string filename)
{
try
{
if (string.IsNullOrEmpty(filename))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
}
BlobStorageService service = new BlobStorageService();
await service.UploadFileStream(filestream, filename, "image/png");
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
catch (Exception ex)
{
base.LogException(ex);
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest));
}
将新图像作为流添加到 blob 容器的代码如下所示。
public async Task UploadFileStream(Stream filestream, string filename, string contentType)
{
CloudBlockBlob blockBlobImage = this._container.GetBlockBlobReference(filename);
blockBlobImage.Properties.ContentType = contentType;
blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());
await blockBlobImage.UploadFromStreamAsync(filestream);
}
最后这是我失败的单元测试。
[TestMethod]
public async Task DeployedImageStreamTests()
{
string blobname = Guid.NewGuid().ToString();
//Arrange
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes($"This is a blob called {blobname}."))
{
Position = 0
};
string url = $"http://mywebapi/api/imagesstream?filestream={stream}&filename={blobname}";
Console.WriteLine($"DeployedImagesTests URL {url}");
HttpContent content = new StringContent(blobname, Encoding.UTF8, "application/json");
var response = await ImagesControllerPostDeploymentTests.PostData(url, content);
//Assert
Assert.IsNotNull(response);
Assert.IsTrue(response.IsSuccessStatusCode); //fails here!!
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
我得到的错误是 值不能为空。 参数名称:来源
这是使用 Web API 将图像流上传到 Azure blob 存储的正确方法吗?我可以毫无问题地处理图像文件,并且现在我正在尝试使用流上传时才遇到这个问题。
【问题讨论】:
-
您遇到的错误的堆栈跟踪是什么(即,哪一行代码引发了错误)?
标签: c# asp.net azure asp.net-web-api azure-blob-storage