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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With