使用参数调用Azure函数中的GET API

fumotvh3  于 2022-12-24  发布在  其他
关注(0)|答案(1)|浏览(141)

我正在尝试实现一个Azure函数,它将ID作为输入并根据该ID检索数据。基本上,Azure函数将调用另一个API,并从中获取数据。我面临着无法将ID作为参数传递的问题。
应用编程接口(. NET)

[HttpGet]
        [Route("{id:guid}")]
        public async Task<IActionResult> GetContact([FromRoute] Guid id)
        {
            var contact = await dbContext.Contacts.FindAsync(id);

            if (contact == null)
            {
                return NotFound();
            }

            return Ok(contact);
        }
    • 功能**
[FunctionName("GetSingleContact")]
        public async Task<IActionResult> GetContact(
            [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Get), Route = null)] HttpRequest req,
            ILogger log)
        {
            try
            {

                var client = _httpClientFactory.CreateClient();
                string id = req.Query["id"];//Null
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                dynamic data = JsonConvert.DeserializeObject(requestBody);
                id ??= data?.id;

                HttpResponseMessage httpResponseMessage = await client.GetAsync($"https://localhost:7209/api/Contacts/{id}");

                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var content = httpResponseMessage.Content;
                    var data1 = await content.ReadAsStringAsync();
                    return new OkObjectResult(data1);
                }

            }
            catch(Exception ex)
            {
                return new BadRequestObjectResult(ex.Message);
            }
            
            return new BadRequestObjectResult("Problem");
        }

每次我传递ID时它都是空的。这是怎么回事?

ubof19bj

ubof19bj1#

它应该在http触发器中工作,方法是设置如下路由参数:

[FunctionName("GetSingleContact")]
public async Task<IActionResult> GetContact(
            [HttpTrigger(AuthorizationLevel.Anonymous, 
            nameof(HttpMethods.Get), Route = "{id}")] HttpRequest req, 
            string id,
            ILogger log)
{
 //use the id
}

有关详细信息,请阅读:https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-http-webhook-trigger?tabs=in-process%2Cfunctionsv2&pivots=programming-language-csharp#customize-the-http-endpoint

相关问题