C# 使用ASP.NET Web API将映像添加到Azure blob存储失败
我有一个Azure blob容器用于存储图像。我还有一套ASP.NET Web API方法,用于添加/删除/列出此容器中的blob。如果我将图像上传为文件,这一切都会起作用。但我现在想上传的图像作为一个流,我得到一个错误C# 使用ASP.NET Web API将映像添加到Azure blob存储失败,c#,asp.net,azure,asp.net-web-api,azure-blob-storage,C#,Asp.net,Azure,Asp.net Web Api,Azure Blob Storage,我有一个Azure blob容器用于存储图像。我还有一套ASP.NET Web API方法,用于添加/删除/列出此容器中的blob。如果我将图像上传为文件,这一切都会起作用。但我现在想上传的图像作为一个流,我得到一个错误 public async Task<HttpResponseMessage> AddImageStream(Stream filestream, string filename) { try { if
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));
}
最后,我的单元测试失败了
[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存储的正确方法吗?我有它的工作与图像文件没有问题,只有得到这个问题,现在我正试图上传使用流
这是使用Web API将图像流上载到Azure blob存储的正确方法吗?我有它的工作与图像文件没有问题,只有得到这个问题,现在我正试图上传使用流
根据您的描述和错误消息,我发现您将url中的流数据发送到web api
根据这篇文章:
Web API使用以下规则绑定参数:
如果参数是“简单”类型,Web API将尝试从URI获取值。简单类型包括.NET基本类型(int、bool、double等),加上TimeSpan、DateTime、Guid、decimal和string,再加上任何带有可从字符串转换的类型转换器的类型。(稍后将详细介绍类型转换器。)
对于复杂类型,Web API尝试使用媒体类型格式化程序从消息体读取值
在我看来,流是一个复杂的类型,因此我建议您可以将其作为主体发布到web api中
此外,我建议您可以包装一个文件类,并使用Newtonsoft.Json将其转换为Json作为消息内容
更多详细信息,请参考以下代码。
文件类:
public class file
{
//Since JsonConvert.SerializeObject couldn't serialize the stream object I used byte[] instead
public byte[] str { get; set; }
public string filename { get; set; }
public string contentType { get; set; }
}
Web Api:
[Route("api/serious/updtTM")]
[HttpPost]
public void updtTM([FromBody]file imagefile)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("aaaaa");
var client = storageAccount.CreateCloudBlobClient();
var container = client.GetContainerReference("images");
CloudBlockBlob blockBlobImage = container.GetBlockBlobReference(imagefile.filename);
blockBlobImage.Properties.ContentType = imagefile.contentType;
blockBlobImage.Metadata.Add("DateCreated", DateTime.UtcNow.ToLongDateString());
blockBlobImage.Metadata.Add("TimeCreated", DateTime.UtcNow.ToLongTimeString());
MemoryStream stream = new MemoryStream(imagefile.str)
{
Position=0
};
blockBlobImage.UploadFromStreamAsync(stream);
}
测试控制台:
using (var client = new HttpClient())
{
string URI = string.Format("http://localhost:14456/api/serious/updtTM");
file f1 = new file();
byte[] aa = File.ReadAllBytes(@"D:\Capture2.PNG");
f1.str = aa;
f1.filename = "Capture2";
f1.contentType = "PNG";
var serializedProduct = JsonConvert.SerializeObject(f1);
var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
var result = client.PostAsync(URI, content).Result;
}
您得到的错误的堆栈跟踪是什么(即,哪行代码抛出了错误)?这是有道理的。我将尝试一下,看看它是否能解决问题。感谢您提供的信息。我最初在将流转换为JSON时遇到问题,但我设法解决了这个问题。这个解决方案现在起作用了,所以我将它标记为已接受的答案。
using (var client = new HttpClient())
{
string URI = string.Format("http://localhost:14456/api/serious/updtTM");
file f1 = new file();
byte[] aa = File.ReadAllBytes(@"D:\Capture2.PNG");
f1.str = aa;
f1.filename = "Capture2";
f1.contentType = "PNG";
var serializedProduct = JsonConvert.SerializeObject(f1);
var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
var result = client.PostAsync(URI, content).Result;
}