c# - 如何在 Azure API 函数中返回变量并通过移动应用程序中的 InvokeApiAsync 函数读取它
问题描述
在我的移动应用程序中调用 InvokeApiAsync() 时,我想返回在 Azure 中创建的 Blob 的名称
移动应用程序中的功能:
private const string PhotoResource = "photo";
public async Task UploadPhoto(MediaFile photo)
{
using (var s = photo.GetStream())
{
var bytes = new byte[s.Length];
await s.ReadAsync(bytes, 0, Convert.ToInt32(s.Length));
var content = new
{
Photo = Convert.ToBase64String(bytes)
};
var json = JToken.FromObject(content);
await Client.InvokeApiAsync(PhotoResource, json);
}
}
Azure 函数 - run.csx:
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,
ILogger log)
{
dynamic data = await req.Content.ReadAsAsync<object>();
string photo = data?.Photo;
var imageBytes = Convert.FromBase64String(photo);
var connectionString =
ConfigurationManager.AppSettings["BlobStorageConnectionString"];
CloudStorageAccount storageAccount;
CloudStorageAccount.TryParse(connectionString, out storageAccount);
var blobClient = storageAccount.CreateCloudBlobClient();
var blobContainer = blobClient.GetContainerReference("beerphotos");
var blobName = Guid.NewGuid().ToString();
var blob = blobContainer.GetBlockBlobReference(blobName);
blob.Properties.ContentType = "image/jpg";
await blob.UploadFromByteArrayAsync(imageBytes, 0, imageBytes.Length);
log.LogInformation($"Blob {blobName} created");
//return req.CreateResponse(HttpStatusCode.OK);
//NEW CODE ADDED AFTER ANSWER FROM JASON
var response = req.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent(blobName);
return response;
}
如果我尝试写 return req.CreateResponse(HttpStatusCode.OK,blobName); 我收到此错误:run.csx(35,16):错误 CS1501:方法“CreateResponse”没有重载需要 2 个参数
我在天蓝色功能中错过了什么?
在我的移动应用程序中调用 InvokeApiAsync() 应该如何读取 blob 名称?
编辑:
在 Azure 函数中添加新代码后,我得到以下未处理异常:Newtonsoft.Json.JsonReaderException:输入字符串“813255ca-02d0-4feb-8012-2d5a0ad49464”不是有效数字。路径 '',第 1 行,位置 36。
当移动函数中的 Client.InvokeApiAsync(PhotoResource, json) 随响应返回时,将引发异常。'813255ca-02d0-4feb-8012-2d5a0ad49464' 实际上是照片的名称。
解决方案
返回响应正文中的数据
return req.CreateResponse(HttpStatusCode.OK) { Content = new StringContent(blobName) };
然后在调用它时
var resp = await Client.InvokeApiAsync(PhotoResource, json);
if (resp.StatusCode == HttpStatusCode.OK) {
var guid = await resp.Content.ReadAsStringAsync();
}
推荐阅读
- ruby - 如何从 BasicObject 中访问 Ruby 类型名称
- javascript - 数组元素的依从性属性 i
- angular - 如何为电子邮件制作输入掩码?
- python - 有选择地为一段(打包的)python .app 请求 root 访问权限
- node.js - 尝试使用 Grunt.JS 启动本地网络时出现问题
- vbscript - 通过 vbs 更新 Windows
- r - 两个相同类型的数据帧在函数中执行不同
- linux - 计算 shell 脚本每一步的时间并显示总执行时间
- amazon-dynamodb - 逻辑节点是负责连续的密钥范围还是随机的密钥集
- javascript - Angular - mat-grid-list 不显示经过的孩子