asp.net-core - 如何从 MVC Controller 使用 Azure Function

标签 asp.net-core azure-functions

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

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

最佳答案

下面是如何将 azure 函数调用到 Controller 中的示例。

我有一个简单的 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;
        }
    }

Controller 调用的测试函数:

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

希望你明白。即插即用。

关于asp.net-core - 如何从 MVC Controller 使用 Azure Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919887/

相关文章:

c# - 无法在 EF Core : "42P07: relation "AspNetRoles"already exists"中使用迁移

c# - LinkGenerator GetPathByPage 对于区域页面返回 null

c# - 如何在Azure Functions V2中记录到azure应用程序日志?

AKS 中的 Azure Functions HttpTrigger 键

c# - .NET MVC 6/vNext UserValidator 允许字母数字字符

c# - 是否可以在 ASP.NET Web API 中的模型/DTO 上定义路由(类似于 ServiceStack)?

asp.net-mvc - 添加基于策略的授权会跳过 JWT 持有者 token 身份验证检查吗?

javascript - Azure:如何在传入的 blob/文件进入 blob 存储之前对其进行扫描?

c# - 使用 VS2017 在 Azure Function 中复制 Blob

c# - appsettings.json 在部署为 Azure Function App 容器时可以正确读取,但在部署为简单的 Azure Function App 时则无法正确读取