Web Api Dash在变量名模型绑定器中

时间:2014-07-10 20:54:21

标签: .net asp.net-web-api mailgun

我想将Mailgun的webhook实现到我的.Net Web API应用程序中,但是他们POST的一些参数已经在其中出现了问题。我该如何解决这个问题?

他们发布的内容示例:

client-type=browser&city=San+Francisco&domain=telzio.com&device-type=desktop&my_var_1=Mailgun+Variable+%231&country=US&region=CA&client-name=Chrome&user-agent=Mozilla%2F5.0+%28X11%3B+Linux+x86_64%29+AppleWebKit%2F537.31+%28KHTML%2C+like+Gecko%29+Chrome%2F26.0.1410.43+Safari%2F537.31&client-os=Linux&my-var-2=awesome&ip=50.56.129.169&recipient=alice%40example.com&event=opened&timestamp=1405017113&token=6khi46bvupa1358v0b3iy29kwumpbajb3ioz4illb6v9bbqkp6&signature=88f46b9ba63ff475bbb3ab193696cf45bf2f25e7e62b44f1e492ff4e085730dd

我的模特:

public class MailgunModel
{
    public string City { get; set; }
    public string Domain { get; set; }
    public string Country { get; set; }
    public string Region { get; set; }
    public string Ip { get; set; }
    public string Recipient { get; set; }
    public string Event { get; set; }
    public long Timestamp { get; set; }
    public string Token { get; set; }
    public string Signature { get; set; }

    public string ClientType get; set; }
    public string DeviceType { get; set; }
    public string ClientName { get; set; }
    public string UserAgent { get; set; }
    public string ClientOs { get; set; }
}

2 个答案:

答案 0 :(得分:5)

One of the easiest ways is to receive a FormDataCollection and access the variables you need. It's lame because you have to map manually each property but it works for simple scenarios.

public IHttpActionResult AppointmentMessage(FormDataCollection data)
{
    if (data != null)
    {
        var msg = new MailGunMessage();
        msg.From = data["from"];
        msg.To = data["to"];
        msg.Subject = data["subject"];
        msg.BodyHtml = data["body-html"];
        msg.BodyPlain = data["body-pain"];
        // ... and so on
    }
    return this.Ok();
 }

An other options is to use a custom model binder on your model like described here: https://stackoverflow.com/a/4316327/1720615

答案 1 :(得分:0)

您仍然可以将模型用作操作的参数,并通过Request.Params例如获取虚线值。 HttpContext.Current.Request.Params["device-type"]

这样,您将可以使用强类型模型而不是FormDataCollection。