如何从MVC Controller消耗Azure功能

时间:2019-07-07 06:33:03

标签: asp.net-core azure-functions

我已经创建并发布了用于搜索功能的Azure函数(HTTP触发)。当我在搜索框中键入ID并单击“搜索”时,它应调用Azure函数并取回结果。

如何将Azure Function与.NETCore中的Controller Action集成?

1 个答案:

答案 0 :(得分:0)

以下是示例如何将azure函数调用到控制器中。

我有一个简单的azure函数,该函数会在调用后返回名称和电子邮件。让我们看下面的例子:

public class InvokeAzureFunctionController : ApiController
    {
        // GET api/<controller>
        public async System.Threading.Tasks.Task<IEnumerable<object>> GetAsync()
        {
            HttpClient _client = new HttpClient();
            HttpRequestMessage newRequest = new HttpRequestMessage(HttpMethod.Get, "http://localhost:7071/api/FunctionForController");
            HttpResponseMessage response = await _client.SendAsync(newRequest);

            dynamic responseResutls = await response.Content.ReadAsAsync<dynamic>();
            return responseResutls;
        }
    }

控制器调用的测试功能:

public static class FunctionForController
    {
        [FunctionName("FunctionForController")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            // parse query parameter
            string name = req.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
                .Value;

            if (name == null)
            {
                // Get request body
                dynamic data = await req.Content.ReadAsAsync<object>();
                name = data?.name;
            }

            ContactInformation objContact = new ContactInformation();

            objContact.Name = "From Azure Function";
            objContact.Email = "fromazure@function.com";

            return req.CreateResponse(HttpStatusCode.OK, objContact);
        }
    }

我使用过的简单ContactInformation类:

   public class ContactInformation
    {
        public string Name { get; set; }
        public string Email { get; set; }
    }

PostMan测试:

我已经从Post Man调用了controller action,并且它通过local controller action从我的本地azure函数成功返回了数据。请参见以下屏幕截图:

enter image description here

希望您能理解。只需即插即用。