Create a C# .net core webhook for a Dialogflow chatbot

Fouad Roumieh
Voice Tech Podcast
Published in
5 min readAug 15, 2019

In the previous article: Build a chatbot using C# and Dialogflow we’ve seen how to setup a basic chatbot functionality on Dialogicflow console. In this article we will move a step further to show you how to integrate the chatbot with a webhook that generates dynamic responses for your chatbot, it is also known as Fulfillment in Dialogflow.

Create the VS project

I’m using VS 2019 and will be adding an C# Asp.net Core Web Application solution, give the project a name: HotelBooking or any other name you prefer. In the next step when you are prompted to choose a template for the project select the Api one as below:

Go to nuget console and install the package `Google.Cloud.Dialogflow.V2`, this is Google client library to access the Google Dialogflow API.

Now your project is ready for some coding!

Write the Webhook code

By default VS will create ValuesController, let’s rename to BookingControlleralso rename the file to match the class name.

So our webhook will be a HttpPost endpoint that receives a request from the Dialogflow api, parse that request and prepare a response for it. On the api official documentation here there is a basic example of how to parse that request and reply, so I’ll follow with minor changes for our scenario. Below is what the final code will look like, nothing fancy or complicated about it. The purpose of it is just to show how to hookup request from your chatbot api and generate a reply:

[Route(“api/[controller]”)][ApiController]public class BookingController : ControllerBase{// A Protobuf JSON parser configured to ignore unknown fields. This makes// the action robust against new fields being introduced by Dialogflow.private static readonly JsonParser jsonParser =new JsonParser(JsonParser.Settings.Default.WithIgnoreUnknownFields(true));[HttpPost]public ContentResult DialogAction(){// Parse the body of the request using the Protobuf JSON parser,// *not* Json.NET.WebhookRequest request;using (var reader = new StreamReader(Request.Body)){request = jsonParser.Parse<WebhookRequest>(reader);}double totalAmount = 0;double totalNights = 0;double totalPersons = 0;if (request.QueryResult.Action == “book”){//Parse the intent paramsvar requestParameters = request.QueryResult.Parameters;totalPersons = requestParameters.Fields[“totalPersons”].NumberValue;totalNights = requestParameters.Fields[“totalNights”].NumberValue;totalAmount = totalNights * 100;}// Populate the responseWebhookResponse response = new WebhookResponse{FulfillmentText = $”Thank you for choosing our hotel, your total amount for the {totalNights} nights for {totalPersons} persons will be {totalAmount} USD.”};// Ask Protobuf to format the JSON to return.// Again, we don’t want to use Json.NET — it doesn’t know how to handle Struct// values etc.string responseJson = response.ToString();return Content(responseJson, “application/json”);}}

Build better voice apps. Get more articles & interviews from voice technology experts at voicetechpodcast.com

Integrate the Webhook with Dialogflow

The next step is to deploy your webhook to a public provider so it can be acessed from Dialogflow side, I deployed itto heroku and you can deploy to any other service provider you are familiar with. I will not go into the details of the heroku deployment it’s beyond the scope of this article, but the internet has a lot of info on: how to deploy .net core app to heroku.

We are going to attach the intent that we created in our previous article Booking Info and to do that:

  1. Go to the Dialogflow console and click on Fullfilment menu item on the left.
  2. Toggle the Enabled button and fill in the Url textbox with the url value of your you webhook that you deployed, it will be something like https://[yourdomainname]/api/booking
  3. Next go to the Intents section and click Booking Info intent then scroll down to Fulfillments and turn on Enable webhook call for this item

What we did here is basically telling the Dialogic api that whenever a message from the end user matches this intent the request should be forwarded to the webhook that we configured earlier and response will be generated via the webhook also.

Now what happen if the webhook is down? Under the same intent Booking Info create a text response as `I’m sorry, but I’m having a problem processing your request, please try again later.` That response will be returned whenver there is an issue communicating with the webhook, you can try it by putting a fake url for your webhook for example.

If everything is OK type the message in the simulator that matches the specified intents and you should get a response same as the below:

As you can see the above response is the one coming from the webhook!

How to test the webhook locally

If you want to debug through the webhook code locally by the time you developing iy, you can use libraries like ngrok. As per the documentation:

ngrok allows you to expose a web server running on your local machine to the internet. Just tell ngrok what port your web server is listening on.

The other trick that you can do is by using the request sent via Dialogflow to the webhook and by using a tool like postman you can post the request to your local instance and debug. To get that request, type a message in the simulator on Dialogflow and then click on the Diagnostic Info by the bottom right and open Fulfillment Request tab and that will be the json object that your webhook will receive via a post message.

And once you post it via a tool like postman as below, you can debug it locally in VS:

The above webhook will give you a good example of how to connect your chatbot to your back-end api which helps return more rich info for the end user.

Check this article on: Integrate Dialogflow chatbot with Skype channel to see a close real world usage scenario of chatbots.

I hope you find this a good reading!

--

--