【问题标题】:How to use C# and Google.Cloud.Dialogflow.Cx.V3 to generate valid Google DialogFlow CX webhook response JSON如何使用 C# 和 Google.Cloud.Dialogflow.Cx.V3 生成有效的 Google DialogFlow CX webhook 响应 JSON
【发布时间】:2022-07-20 11:31:18
【问题描述】:

我已经使用 C# 和 ASP.NET Core 创建了一个 webhook,以尝试生成对 DialogFlow 的 webhook 响应,但我真的很难使用 Google.Cloud.Dialogflow.Cx.V3 创建一个有效负载类似于我知道我需要生产的有效载荷。我意识到我可以重新“手动创建”JSON 字符串,但如果可以的话,我宁愿使用这个库。这是我需要创建的响应:

{
  fulfillmentResponse: {
    messages: [
      {
        payload: {
          plainText: "Details for order ID: {order_id}",
          richContent: [
            {
              type: "card",
              title: "{order_id}",
              text: [
                "<span class='subtitle'>Ordered</span>",
                "{order_date}",
                "<span class='subtitle'>Status</span>",
                "{order_status}",
                "<span class='subtitle'>Store</span>",
                "{order_store}",
                
              ],
              link: {
                url: "{tracking_link}"text: "Track Shipment"
              }
            }
          ]
        }
      }
    ]
  }
}

这是我的代码当前生成的(就目前而言,我只是想重新创建纯文本部分。我什至还没有接触到richContent)

{
    "webhookResponse": {
        "fulfillmentResponse": {
            "messages": [
                {
                    "text": null,
                    "payload": {
                        "fields": {
                            "plainText": {
                                "nullValue": 0,
                                "numberValue": 0,
                                "stringValue": "Details for Order: 11607",
                                "boolValue": false,
                                "structValue": null,
                                "listValue": null,
                                "kindCase": 3
                            }
                        }
                    },
                    "conversationSuccess": null,
                    "outputAudioText": null,
                    "liveAgentHandoff": null,
                    "endInteraction": null,
                    "playAudio": null,
                    "mixedAudio": null,
                    "telephonyTransferCall": null,
                    "messageCase": 2
                }
            ],
            "mergeBehavior": 0
        },
        "pageInfo": null,
        "sessionInfo": null,
        "payload": null,
        "targetPage": "",
        "targetFlow": "",
        "transitionCase": 0,
        "targetPageAsPageName": null,
        "targetFlowAsFlowName": null
    }
}

还有各种附加字段,以及消息似乎被包装在“webhookResponse”中,而不是从fulfillmentResponse 开始。我有点卡住了。这是我迄今为止创建响应的代码:

public class OrderStatusResponse : DialogFlowResponse
{

    public OrderStatusResponse(OrderStatusDto orderStatus, string requestId)
    {
        this.webhookResponse = new WebhookResponse();
        WebhookResponse.Types.FulfillmentResponse fulfillmentResponse = new WebhookResponse.Types.FulfillmentResponse();
        this.webhookResponse.FulfillmentResponse = fulfillmentResponse;
        var plainText = new Google.Protobuf.WellKnownTypes.Value();
        var payload = new Google.Protobuf.WellKnownTypes.Struct();
        plainText.StringValue = $"Details for Order: {orderStatus.OrderResults.First().OrderId}";
        var responseItem = new ResponseMessage();
        responseItem.Payload = payload; 
        responseItem.Payload.Fields.Add("plainText", plainText);
        fulfillmentResponse.Messages.Add(responseItem);

    }
}

我只是从下面的控制器中将其作为 IActionResult 中的“response”返回:

[HttpPost]
[SwaggerResponse(200, "OrderStatusResponse", typeof(Api.Internal.Orders.Responses.OrderStatusResponse))]
[SwaggerResponse(400, "OrderNotFoundException", typeof(OrderNotFoundException))]
[SwaggerResponse(400, "InvalidRequestException", typeof(InvalidRequestException))]
[Route("search/")]
public async Task<IActionResult> GetOrdersBySearch([FromBody] OrderStatusRequest request)
{
    requestId = ControllerHelper.GetRequestId(Request.HttpContext);

    try
    {
        _logger.LogInformation($"Starting request {requestId}");
        var response = await _orderService.GetOrdersBySearch(request, requestId);
        return Ok(response);
    }
    catch (OrderNotFoundException oex)
    {
        _logger.LogError(oex.ToString());
        return BadRequest(oex.Problem);
    }
    catch (InvalidRequestException irex)
    {
        _logger.LogError(irex.ToString());
        return BadRequest(irex.Problem);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.ToString());
        return StatusCode(500, new FriendlyErrorException(requestId).Problem);
    }
}

【问题讨论】:

  • 您好,您能否提供完整的示例代码和您所遵循的文档以生成 JSON 响应?
  • 抱歉,我应该关闭这个问题。我最终没有使用 Google protobuf 库,而只使用标准 C# POCO 序列化/反序列化 JSON。工作正常:)

标签: c# asp.net-core google-cloud-platform protocol-buffers dialogflow-cx


【解决方案1】:

最后,对我来说,解决方案就是使用标准 C# POCO 和 System.Text.JSON 进行序列化/反序列化。这很好用,我不需要参考 Google protobuf 库。

【讨论】:

    【解决方案2】:

    Google.Cloud.Dialogflow.Cx.V3 客户端库(或任何 Google Cloud .NET library)类派生自 Protobuf definitions - 使用 Google.Protobuf.JsonFormatter 创建有效的 JSON 对象。

    类似这样,response 是一个 SDK 对象

    using Google.Protobuf;
    
    ...
    
    JsonFormatter jf = new JsonFormatter(new JsonFormatter.Settings(true));
    Console.WriteLine(jf.Format(response));
    

    【讨论】:

      猜你喜欢
      • 2021-05-06
      • 2021-06-08
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多