Facebook Messenger API在c#asp.net mvc应用程序中的实现

本文关键字:应用程序 实现 mvc net Messenger API c#asp Facebook | 更新日期: 2023-09-27 17:58:59

在类似的node.js实现中

app.post('/webhook/', function(req, res) {  
console.log("message received " + req.body);
if(!req.body){
    console.log("no request body found");
    res.sendStatus(200);
    return;
}
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
    event = req.body.entry[0].messaging[i];
    sender = event.sender.id;
    console.log("sender " + event.sender + ", message " + event.message.text);
    if (event.message && event.message.text) {
        text = event.message.text;
        // Handle a text message from this sender
        sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
    }
}
res.sendStatus(200);
});

如何在.net mvc应用程序中实现它。特别是如何实现这条线路的

app.post('/webhook/', function(req, res)

在控制器中使用mvc。

Facebook Messenger API在c#asp.net mvc应用程序中的实现

最后搜索并收集一些数据

facebook发布类似的模型json数据

{
"entry": [{
    "messaging":[{
        "sender": {
          "id": "1126306517444636"
        },
        "recipient": {
          "id": "514501872066958"
        },
        "timestamp": 1469541638971,
        "message": {
          "mid": "mid.1469541638961:5d5d5d5bf1194eb824",
          "seq": 64,
          "text": "hi"
        }
        }
        ]
   }
]
}

所以我们必须创建这样的模型

public class Sender
{
   public string id { get; set; }
}
public class Recipient
{
    public string id { get; set; }
}
public class Message
{
    public string mid { get; set; }
    public int seq { get; set; }
    public string text { get; set; }
}
public class Messaging
{
    public Sender sender { get; set; }
    public Recipient recipient { get; set; }
    public long timestamp { get; set; }
    public Message message { get; set; }
}
public class Entry
{
    public List<Messaging> messaging { get; set; }
}
public class RootObject
{
     public List<Entry> entry { get; set; }
}

和控制器类

public ActionResult Webhook(RootObject model)
{
    ....................................
}