如何使用 C# 和 Google.Cloud.Dialogflow.Cx.V3 生成有效的 Google DialogFlow CX webhook 响应 JSON

How to use C# and Google.Cloud.Dialogflow.Cx.V3 to generate valid Google DialogFlow CX webhook response JSON

我已经使用 C# 和 ASP.NET Core 创建了一个 webhook,以便尝试生成对 DialogFlow 的 webhook 响应,但我真的很难使用 Google.Cloud.Dialogflow.Cx.V3 创建一个类似于我知道我需要生产的有效载荷。我意识到我可以退回到 'hand creating' 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);
    }
}

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