2

我正在尝试使用 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 频道。有没有办法在使用 HttpClient 时实现相同的功能?

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

提前感谢您的帮助!

4

2 回答 2

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);
于 2021-02-19T20:41:28.070 回答
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
                }
            }
于 2016-08-02T20:17:33.947 回答