我已经为搜索功能创建并发布了一个 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 函数成功返回了数据。请参见下面的屏幕截图:
希望你明白。即插即用。
关于asp.net-core - 如何从 MVC Controller 使用 Azure Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56919887/