首页 > 解决方案 > 如何在 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' 实际上是照片的名称。

标签: c#azurexamarinmobile

解决方案


返回响应正文中的数据

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();
}

推荐阅读