asp.net-core - 如何从 MVC 控制器使用 Azure 函数
问题描述
我为搜索功能创建并发布了一个 Azure 函数(HTTP 触发)。当我在搜索框中键入 ID 并单击“搜索”时,它应该调用 Azure 函数并返回结果。
如何在 .NETCore 中将 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; }
}
邮递员测试:
我已经controller action
从 Post Man 调用了,它通过local controller action
. 请看下面的屏幕截图:
希望你能理解。现在只需即插即用。
推荐阅读
- linux - MONGODB-ORG 未在 UBUNTU 20.04 上运行
- ui-automation - 想在不包括 GUI 的操作系统上使用空手道 UI 自动化,对 Java 不友好
- android - 声学回声消除和噪音抑制似乎不适用于 Android
- python - 在 Python 中加入由冒号分隔的行
- python-3.x - 函数返回未更新的列表的先前值
- redis - 使用 Spring Data Redis 将 lua 表转换为 java `Map`
- json - Swift - 使用组合解析 JSON,URLSession DataTaskPublisher - 奇怪的格式
- c++ - 与 wchar_t 一起使用时 getlength 抛出错误
- python - 如何为TF2.0+ keras CNN定义一个grad cam函数进行图像分类?
- matlab - 为什么在MATLAB中使用`subs`并直接输入向量公式结果不相等?