Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twilio Messaging Webhook - Unsupported Media Type - Asp.net Core 3.1 API

I have an asp.net core (3.1) web api with an endpoint to accept the Twilio Messaging Webhook. When I run it locally from postman it works, when the webhook posts, I get an 415 "Unsupported Media Type"

[ApiController]
[Route("[controller]")]
public class TwillioController : TwilioController
{
    [HttpPost("ProcessIncomingMessage")]
    public TwiMLResult ProcessIncomingMessage(SmsRequest incomingMessage)
    {
      Console.WriteLine($"Recieved new SMS from {incomingMessage.From}");
      var messagingResponse = new MessagingResponse();
      messagingResponse.Message("The copy cat says: " +
                                incomingMessage.Body);

      return TwiML(messagingResponse);
    }
  }

It works when I have Content-Type:application/json in the header in postman.

I have also tried adding

[Consumes("application/x-www-form-urlencoded")]

as well as

[Consumes("application/xml")]

and both still get the unsupported media type... can not figure out what Twilio is sending over or what I need to do to make it compatibly with their webhook.

like image 835
Brandon Turpy Avatar asked Mar 03 '23 04:03

Brandon Turpy


2 Answers

As the other answers mention, Twilio sends requests with a content type of x-www-form-urlencoded. Actions in controllers annotated with the [ApiController] attribute need to have a [FromForm] attribute on the parameter to work, like this:

[ApiController]
public class TwilioController : ControllerBase
{
    [HttpPost("")]
    public TwiMLResult Post([FromForm] SmsRequest request)
    {
        // do stuff with the SMS request
    }
}

While you can include a [Consumes] attribute, it isn't necessary.

like image 81
Michael Brandon Morris Avatar answered Mar 04 '23 17:03

Michael Brandon Morris


So I realized the ApiController was what was throwing it off. I removed all of the attributes and added the correct routes in startup and it works.

 public class SmsController : TwilioController
  {
    public TwiMLResult WebHook(SmsRequest incomingMessage)
    {
      var messagingResponse = new MessagingResponse();
      if (incomingMessage != null)
      {
        messagingResponse.Message($"The copy cat says: {incomingMessage.Body}");
      }
      else
      {
        messagingResponse.Message($"Recieved SMS but body was null");
      }


      return TwiML(messagingResponse);
    }
  }

Added an endpoint on startup

endpoints.MapControllerRoute(
name: "sms",
pattern: "sms/{Action}",
defaults: new { Controller = "Sms"});

And the webhook URL is https://OURURL/sms/WebHook

like image 31
Brandon Turpy Avatar answered Mar 04 '23 17:03

Brandon Turpy