blue
blue

Reputation: 863

Receive SMS in .net core webapi uinsg Twilio

I am using following code to receive a text message send to Twilio virtual number in my .net core api. My web hook api code is like,

namespace MyNameSpace.Controllers
{
    [Route(Routing.CONTROLLER_PREFIX)]
    public class MfaController : MyControllerBase
    {

        [HttpPost]
        [Route(Constants.Save)]
        [Produces("application/xml")]
        public ActionResult SaveText(TextMessage TextInfo)
        {
            // My save logic here


           return Ok();
        }
    }
}

when I test the code locally then I get a 200 - Ok response in fiddler and postman. But I'm getting error in Twilio console (debugger)

{
    "callbackResult": "SUCCESS",
    "statusCode": 502,
    "body": "VHd...............",
    "cookies": [],
    "headers": {
        "Transfer-Encoding": [
            "chunked"
        ],
        "X-Cache": [
            "MISS from ip-XXX-18-0-xXx"
        ],
        "X-Cache-Lookup": [
            "MISS from ip-XXX-18-0-XXX:3128"
        ],
        "X-Twilio-Reason": [
            "Response does not contain content type"
        ],
        "Date": [
            "Thu, 29 Mar 2018 16:08:10 GMT"
        ],
        "Content-Type": [
            "text/html"
        ]
    }
}

What should be the response type from API? I don't need to send reply message to user, just need to save the text message.

Upvotes: 1

Views: 937

Answers (1)

Corey Weathers
Corey Weathers

Reputation: 419

Twilio Developer Evangelist here...

With the sample code you shared, it looks like you're trying to receive the body of the text, save it off, and then respond to Twilio. Presuming you are using the latest version of the Twilio Nuget package and an HTTP Post request from Twilio, you can use the following code to do it, which we also have on our documentation here.

public ActionResult SaveText([FromBody] string Body)
{
    // Put your save logic here

    // Respond to Twilio
    var response = new MessagingResponse();
    response.Message("");        
    return new ContentResult { Content=response.ToString(), ContentType="application/xml"};
}

The above code uses parameter binding to grab the body off of the POST request. If you'd like you can also include the Twilio.AspNet.Mvc helper library which this blog post uses to make the code a bit cleaner and easier to read.

One last note: I would recommend sending a confirmation to let the sender know that your app has received the message. Let me know if this helps.

Upvotes: 5

Related Questions