尝试使用HttpClient.PostAsync而不是WebClient

时间:2016-08-02 20:13:35

标签: c# httpclient webclient slack namevaluecollection

我正在尝试使用HttpClient将NameValueCollection发布到特定的Url。我有使用WebClient的代码,但我试图弄清楚是否可以使用HttpClient。

下面,您将找到使用WebClient的工作代码:

var payloadJson = JsonConvert.SerializeObject(new { channel, username, text });

using (var client = new WebClient())
{
    var data = new NameValueCollection();
    data["payload"] = payloadJson;

    var response = client.UploadValues(_uri, "POST", data);

    var responseText = _encoding.GetString(response);
}

我使用此代码尝试使用Web集成将消息发布到Slack Channel。有没有办法在使用HttpClient时实现相同的功能?

我尝试使用HttpClient时收到的Slack错误是" missing_text_or_fallback_or_attachment"。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

使用HttpClient

      using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://yourdomain.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                 var data = new NameValueCollection();
                 data["payload"] = payloadJson;

                StringContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

                try
                {
                    HttpResponseMessage response = await client.PostAsync("api/yourcontroller", content);
                    if (response.IsSuccessStatusCode)
                    {
                        //MessageBox.Show("Upload Successful", "Success", MessageBoxButtons.OK);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

答案 1 :(得分:0)

当您在问题中标记 #slack 时,我建议您使用 Slack.Webhooks nuget 包。

我发现的示例用法在这里;

https://volkanpaksoy.com/archive/2017/04/11/Integrating-c-applications-with-slack/

var url = "{Webhook URL created in Step 2}";

var slackClient = new SlackClient(url);

var slackMessage = new SlackMessage
{
    Channel = "#general",
    Text = "New message coming in!",
    IconEmoji = Emoji.CreditCard,
    Username = "any-name-would-do"
};

slackClient.Post(slackMessage);