Home > Blockchain >  Why does my Twilio MessagingResponse not work?
Why does my Twilio MessagingResponse not work?

Time:11-02

The following Twilio code doesn't work. This is my webhook handler in an ASP.NET (Core) 6.0 app.

[AllowAnonymous]
[HttpPost]
[Route("webhook-url")]
public IActionResult PostTwilioMessageReceived([FromForm] TwilioMessageReceivedFormModel formModel)
{
    // logging code etc.

    var response = new Twilio.TwiML.MessagingResponse();
    response.AddText($"You sent '{formModel.Body}' but our systems are dumb and can't process this yet.");
    
    return new TwiMLResult(response);
}

There are no errors. I don't receive the message, and my delivery status webhook doesn't appear to be called.

The method above is called as I see it in my logs.

Note - There is no "to" address. I have adapted sample code from Twilio's documentation which also does nothing to either read the sender address or configure the response with a recipient or other correlation ID.

https://www.twilio.com/docs/whatsapp/tutorial/send-and-receive-media-messages-whatsapp-csharp-aspnet#generate-twiml-in-your-application


I've modified my logging to make doubly sure my webhook is being called. It is. And in Twilio's log there's no acknowledgement of the reply my webhook attempts to produce.

To be clear, the code above is using Twilio's libraries.

CodePudding user response:

It's hard to say what caused this without seeing an error or message log. You should be able to see something in the "Monitor" in the console (more details here).

I've had similar issues in the past with Node.js and the problem was there that I forgot to set the content-type of the response to text/xml. But I'm not sure if this is required in your C# code.

CodePudding user response:

The TwiML output of your application would be:

<Response>You sent '...' but our systems are dumb and can't process this yet.</Response>

Unfortunately, that isn't valid TwiML, instead it should look like this:

<Response>
   <Message>You sent '...' but our systems are dumb and can't process this yet.</Message>
</Response>

This will respond with a message to the sender. To do this, use the .Message method instead of .AddText:

response.Message($"You sent '{formModel.Body}' but our systems are dumb and can't process this yet.");

Everything else looks fine in your code AFAIK.


Aside: If all you need to do is to respond to the current sender with a single message, you can also respond with plain text and the text/plain content type.

  • Related