首页 > 解决方案 > 如何从 MVC 控制器使用 Azure 函数

问题描述

我为搜索功能创建并发布了一个 Azure 函数(HTTP 触发)。当我在搜索框中键入 ID 并单击“搜索”时,它应该调用 Azure 函数并返回结果。

如何在 .NETCore 中将 Azure 功能与我的控制器操作集成?

标签: asp.net-coreazure-functions

解决方案


这是如何将 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; }
    }

邮递员测试:

我已经controller action从 Post Man 调用了,它通过local controller action. 请看下面的屏幕截图:

在此处输入图像描述

希望你能理解。现在只需即插即用。


推荐阅读