![](/img/trans.png)
[英]How to call external api with Azure function with POST method with request body data
[英]How to retrieve bytes data from request body in Azure Function App
在 Python 中,我將圖像轉換為字節。 然后,我像這樣將字節傳遞給 Azure HTTP 觸發器函數應用端點 URL(Azure 門戶),就像調用 Azure 認知服務時一樣。
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 門戶上的函數應用中檢索字節數據。 我嘗試了以下(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 認知服務是如何做到的!
提前致謝。
不要使用ReadToEndAsync()
,而是使用MemoryStream()
。 ReadToEndAsync()
用於讀取字符串緩沖區,這可能會弄亂傳入的字節數據。 使用CopyToAsync()
然后將內存流轉換為字節數組以保留傳入的字節數據。
public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
//string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
MemoryStream ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
byte[] imageBytes = ms.ToArray();
log.LogInformation(imageBytes.Length.ToString());
// ignore below (not related)
string finalString = "Upload succeeded";
Returner returnerObj = new Returner();
returnerObj.returnString = finalString;
var jsonToReturn = JsonConvert.SerializeObject(returnerObj);
return new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
};
}
public class Returner
{
public string returnString { get; set; }
}
參考/靈感來源: https : //weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.