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

Viewed 876

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.

3 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.

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

Here are the details of what Twilio is sending to your application, so application/x-www-form-urlencoded is 100% correct.

Webhooks FAQ

"For inbound text messages, Twilio will send an HTTP POST request to your server with a body that uses the application/x-www-form-urlencoded encoding. View the list of parameters sent in that request."

If it works when you set the Content-Type:application/json in the header in postman, then something is off since it should expect and consume application/x-www-form-urlencoded.

Related