如何在Azure Function App中从请求正文中检索字节数据

时间:2019-03-01 12:23:36

标签: c# python byte azure-functions azureportal

在Python中,我将图像转换为字节。然后,像通常在calling Azure cognitive services时一样,将字节传递给Azure HTTP触发器函数应用程序终结点URL(Azure Portal)。

image_path = r"C:\Users\User\Desktop\bicycle.jpg"
image_data = open(image_path, "rb").read()
print(len(image_data)) # print length to compare later
url = "https://xxxx.azurewebsites.net/api/HTTPTrigger1........."
headers    = {'Content-Type': 'application/octet-stream'}
response = requests.post(url, headers=headers,
                             data=image_data)

但是,我不知道如何在Azure Portal上的功能应用程序中检索字节数据。我尝试了以下(C#),但没有成功。看来ReadToEndAsync()并不是要从请求正文中读取字节数据?还是因为HttpRequest

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    byte[] imageBytes = Encoding.ASCII.GetBytes(requestBody); 
    log.LogInformation(imageBytes.Length.ToString());
    // the length logged is totally not the same with len(image_data) in Python

    //ignore the following lines (not related)
    return name != null
    ? (ActionResult)new OkObjectResult("OK")
    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

对此有任何想法吗?我确实知道使用base64字符串的解决方法,但是我真的很好奇Azure认知服务是如何做到的!

谢谢。

1 个答案:

答案 0 :(得分:3)

请勿使用944.95 15116.05 14171.0 141710 0.100000705666502 [ 944.95 945.05000071 945.15000141 ... 15115.74999788 15115.84999859 15115.94999929] ,而应使用ReadToEndAsync()MemoryStream()用于读取字符串缓冲区,它可能会使传入的字节数据混乱。使用ReadToEndAsync(),然后将内存流转换为字节数组,以保留传入的字节数据。

CopyToAsync()

参考/灵感来自: https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers