使用C#,如何构建一个复杂的post对象以便在WebClient帖子中使用?

时间:2014-04-05 15:50:16

标签: c# webclient urbanairship.com

背景

在我的C#中间层,我有一个计划任务,每分钟运行一定的业务逻辑,然后相应地向iOS和Android设备发送推送通知。我使用Urban Airship来促进推送通知,这意味着,在我的代码中,我只是调用他们的API然后他们处理实际推送到各种设备。这是代码的样子:

public static void SendNotice(UaMessageModel messages)
{
    var audience = new NameValueCollection
        {
            {"alias", string.Join(", ", messages.UserIds)}
        };

    var notification = new NameValueCollection
        {
            {"alert", messages.Message}
        };

    var pushNotice = new NameValueCollection
        {
            {"audience", new JavaScriptSerializer().Serialize(audience)},
            {"notification", new JavaScriptSerializer().Serialize(notification)}
        };

    //ToDo: remove "validate" from URL when done testing.
    Utilities.PostWebRequest("https://go.urbanairship.com/api/push/validate/", "Basic XXXXXXXXX", pushNotice, "application/vnd.urbanairship+json; version=3;");
}


public class UaMessageModel
{
    public List<int> UserIds { get; set; }
    public string Message { get; set; }
}

问题

当我在Utilities.PostWebRequest处设置断点并将鼠标悬停在pushNotice上时,我只会看到pushNotice NameValueCollection的键,但没有值。我是否错误地构造了这个NameValueCollection?

更多信息

pushNotice是否构造正确,我仍然没有收到WebClient帖子的任何回复。当我只使用一个简单,扁平的post对象时,此方法有效。这是代码:

public static dynamic PostWebRequest(string url, string token, NameValueCollection obj, string accept)
{
    using (var wc = new WebClient())
    {
        wc.Headers.Add("Authorization", token);
        wc.Headers.Add("Accept", accept);
        return GetObjectFromJson(Encoding.UTF8.GetString(wc.UploadValues(url, "POST", obj)));
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

NameValueCollection不是Dictionary。 JavascriptSerializer不会按预期序列化它。要获得预期结果,您应该将NameValueCollection转换为Dictionary。

    NameValueCollection audience = new NameValueCollection();
    Data.Add("alias", "foobar");
    Data.Add("alias", "foobar2");

要输出值以及将NameValueCollection转换为字典所需的键,如下所示:

    Dictionary<string, string> audienceDictionary = audience.AllKeys.ToDictionary(k => k, k => source[k]));

我们可以在代码中使用Dictionary而不是NameValueCollection:

    Dictionary<string, string> audience = new Dictionary<string, string>();
    audience.Add("alias", string.Join(", ", messages.UserIds));

    Dictionary<string, string> notification = new Dictionary<string, string>();
    notification.Add("alert", messages.Message);

    Dictionary<string, string> pushNotice = new Dictionary<string, string>();
    pushNotice.Add("audience", new JavaScriptSerializer().Serialize(audience));
    pushNotice.Add("notification", new JavaScriptSerializer().Serialize(notification));

修改

另请看一下这个答案:https://stackoverflow.com/a/7003815/2488939