您似乎正在尝试向Azure Function V2 发送POST 请求。见下面代码sn-p。
自定义请求类:
public class Users
{
public string Name { get; set; }
public string Email { get; set; }
}
Azure 函数 V2:
在此示例中,我使用自定义类获取两个参数,并将这两个类属性作为响应返回。
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
//Read Request Body
var content = await new StreamReader(req.Body).ReadToEndAsync();
//Extract Request Body and Parse To Class
Users objUsers = JsonConvert.DeserializeObject<Users>(content);
//As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult
var result = new OkObjectResult(objUsers);
return (IActionResult)result;
}
索取样品:
{
"Name": "Kiron" ,
"Email": "kiron@email.com"
}
邮递员测试:
注意:
您实际上正在寻找await req.Content.ReadAsAsync<>();
从您的函数发送POST 请求所需的。并从
该服务器响应。但请记住,req.Content 不支持阅读 Azure Function V2 中的帖子请求,其中显示了 Function V1 示例 here
另一个例子:
见下面代码sn-p:
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
//Read Request Body
var content = await new StreamReader(req.Body).ReadToEndAsync();
//Extract Request Body and Parse To Class
Users objUsers = JsonConvert.DeserializeObject<Users>(content);
//Post Reuqest to another API
HttpClient client = new HttpClient();
var json = JsonConvert.SerializeObject(objUsers);
//Parsing json to post request content
var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
//Posting data to remote API
HttpResponseMessage responseFromApi = await client.PostAsync("YourRequstURL", stringContent);
//Variable for next use to bind remote API response
var remoteApiResponse = "";
if (responseFromApi.IsSuccessStatusCode)
{
remoteApiResponse = responseFromApi.Content.ReadAsStringAsync().Result; // According to your sample, When you read from server response
}
//As we have to return IAction Type So converting to IAction Class Using OkObjectResult We Even Can Use OkResult
var result = new OkObjectResult(remoteApiResponse);
return (IActionResult)result;
}
希望您理解,如果您仍有任何疑问,请随时分享。谢谢,编码愉快!