从Azure函数调用Web API的最佳方法

时间:2019-05-24 08:25:05

标签: c# azure httpclient azure-functions

实际情况:

我有2个blob triggered azure functions,它们工作正常(一个是v2,另一个是v1) 另一方面,我在我的azure Devops中发布了REST WEB API application(公开了加密和解密流的方法)(实际上仍未部署在azure门户上,实际上,仅将代码添加到了azure Devops存储库中) )

->我想要做的是:

通过我的azure函数中的http调用(调用加密或解密或其他方法)调用Web api应用程序以解密Blob内容。

无需身份验证。

按照最佳实践的顺序,更适合从我的Web api制作API APP,还是将我的Web api项目作为Web App部署到Azure。以及为什么?

有人可以给我一些代码示例吗?

1 个答案:

答案 0 :(得分:1)

似乎您想在API内部调用azure function,这是您理解的代码示例:

在此函数中,我提供了一个MPN编号作为输入,它从3rd party API开始有效,并作为响应返回truefalse

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;
using System.Text;


namespace HaithemKAROUIApiCase.Functions
{
    public static class HaithemKAROUIApiCaseClass
    {
        [FunctionName("HaithemKAROUIApiCaseFunction")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            try
            {
                // Convert all request param into Json object

                var content = req.Content;
                string jsonContent = content.ReadAsStringAsync().Result;
                dynamic requestPram = JsonConvert.DeserializeObject<PartnerMpnModel>(jsonContent);


                // Extract each param
                //string mpnId = requestPram.mpnId;

                if (string.IsNullOrEmpty(requestPram.MpnID))
                {
                    return req.CreateResponse(HttpStatusCode.OK, "Please enter the valid partner Mpn Id!");
                }
                // Call Your  API
                HttpClient newClient = new HttpClient();
                HttpRequestMessage newRequest = new HttpRequestMessage(HttpMethod.Get, string.Format("YourAPIURL?mpnId={0}", requestPram.MpnID));

                //Read Server Response
                HttpResponseMessage response = await newClient.SendAsync(newRequest);
                bool isValidMpn = await response.Content.ReadAsAsync<bool>();


                //Return Mpn status 
                return req.CreateResponse(HttpStatusCode.OK, new PartnerMpnResponseModel { isValidMpn = isValidMpn });
            }
            catch (Exception ex)
            {

                return req.CreateResponse(HttpStatusCode.OK, "Invaild MPN Number! Reason: {0}", string.Format(ex.Message));
            }
        }
    }




   public class PartnerMpnModel
    {
        public string MpnID { get; set; }
    }


    public class PartnerMpnResponseModel
    {
        public bool isValidMpn { get; set; }
    }
}

请求格式

{
    "MpnID": "456987"
}

如果您还有任何疑问,请随时分享。谢谢,祝您编程愉快!