[英]How to POST to an Azure Function (HTTP Trigger) via Postman?
我已經實現了一個 Azure 函數,利用 HTTP 觸發器,與 SendGrid 集成。 預期操作是通過 HTTP 將數據傳遞到 Azure 函數,並將該內容通過電子郵件發送到指定的收件箱。 我的 Azure Function 在 Azure 門戶中測試成功。 換句話說,當我提交這個時,收件箱會收到預期的電子郵件:
但是,當我嘗試通過 Postman POST 到 Azure 函數時,我收到狀態 400“錯誤的請求 - 無效的主機名”。 我嘗試使用我的功能鍵,將鍵作為參數傳遞到 Postman 的 URI 中,或者在標題中作為“x-functions-key”傳遞。 狀態始終為 400。我通過單擊“獲取函數 URL”從 Azure 門戶獲取要發布到的 URL。 作為替代方案,我還嘗試發布到符合以下條件的 URL:
這是我的函數綁定(function.json):
{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"type": "sendGrid",
"name": "$return",
"direction": "out",
"apiKey": "SendGridKey",
"from": "email@email.com",
"to": "email@email.com"
}
]
}
這是函數邏輯(run.csx):
#r "Newtonsoft.Json"
#r "SendGrid"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using SendGrid.Helpers.Mail;
public static SendGridMessage Run(Email req, ILogger log)
{
Guid Id = Guid.NewGuid();
log.LogInformation($"Email generated from websitename via Azure Function. Email ID: {Id}");
SendGridMessage message = new SendGridMessage()
{
Subject = $"From wesbitename. Subj: {req.Subject.Substring(0, 20)}"
};
message.AddContent("text/plain", $"Subject: {req.Subject} \n \n" + $"{req.Content} \n \n" + $"From: {req.CustomerName}, {req.CustomerEmail}");
return message;
}
public class Email
{
public string EmailId { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public string CustomerName { get; set; }
public string CustomerEmail { get; set; }
}
如何通過 HTTP POST 到 Azure 函數? 如何解決 400 錯誤? 謝謝!
有關其他信息,我也在通過 twitter 尋求幫助: https : //twitter.com/devbogoodski/status/1410702335303581697
由於您使用的是 HTTP 觸發器,請確保您的網址采用以下格式
http://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>
添加以下標題:
x-functions-key: A function-specific API key is required. Default if specific is not provided
Content-Type: application/json
然后將您的 json 對象添加到正文
最終,我沒有對 Azure Function 進行任何更改,而是嘗試使用與 Postman 不同的工具進行測試。 我使用了https://reqbin.com/ 。 使用我一直在使用的相同 JSON 正文提交我的 POST 請求並收到狀態代碼 200,內容通過電子郵件發送到指定的收件箱。 所以,問題出在郵遞員身上——不過,在這一點上,我不知道到底是什么。 我已取消選擇每個標題選項,特別是我打算使用的選項除外。 並通過 URL 中的查詢字符串傳遞我的功能鍵,就像我在 Postman 之外的成功測試中所做的那樣,但它在 Postman 中從未奏效。 所以我不完全確定發生了什么。 但是 Azure 函數正在運行。 所以我認為這已經解決了。 感謝您的關注。
如果您對此更感興趣,我在此處對此進行了擴展: https : //bogoodski.medium.com/setting-up-an-azure-function-sendgrid-http-trigger-cfd9c5791201
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.