我正在尝试将JSON http POST的正文输出到Azure服务总线。
Azure文档提供了一个示例,但这是基于时间的函数触发器,而不是HTTP触发器。
https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus#output
这是我的run.csx
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req)
{
// req is the object passed into function
// read in the whole body, await as it reads to the end to get all?
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
// deserialize the request body from JSON to a dynamic object called data
dynamic data = JsonConvert.DeserializeObject(requestBody);
// ok so now we have our request body in JSON in the data variable.
// we need to put it on the service bus somehow
string message = $"Service Bus queue message created at: {DateTime.Now}";
outputSbQueue = message;
return (ActionResult)new OkObjectResult("Ok");
}
还有我的function.json文件:
{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "serviceBus",
"connection": "message-bus_CONNECT",
"name": "outputSbQueue",
"queueName": "test",
"direction": "out"
}
]
}
任何指导表示赞赏。我是新手。这纯粹是为了测试。
UPDATE 5/28/19
这有效:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Net.Http;
public static void Run(HttpRequest req, out string outputSbQueue)
{
// Working as of 5.28.2019 10:48 PM
StreamReader reader = new StreamReader( req.Body );
string text = reader.ReadToEnd();
outputSbQueue = text;
}
但是我没有逻辑将状态返回给呼叫者。
答案 0 :(得分:2)
您提到您需要一个http trigger
。天蓝色函数必须始终具有其Bindings
像这样更改代码的第一行
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequestMessage req, ILogger log,out string outputSbQueue)
{
//Your code
}
您其余的代码看起来不错。最好是用一段try{} catch
块包围代码并捕获任何异常,然后使用log.LogError()
将消息扔到日志中,这是最好的做法。这将帮助您轻松调试功能应用程序。
答案 1 :(得分:2)
基于您的配置,您应该像这样更改函数声明:
public static async Task<IActionResult> Run(HttpRequest req, out string outputSbQueue)
{ ... }
绑定配置应如下所示:
{
"bindings": [
{
"authLevel": "function",
"name": "req",
"type": "httpTrigger",
"direction": "in",
"methods": [
"get",
"post"
]
},
{
"type": "serviceBus",
"connection": "message-bus_CONNECT",
"name": "outputSbQueue",
"queueName": "test",
"direction": "out"
}
]
}
除此之外,一切看起来还不错。