繁体   English   中英

尝试使用 HttpClient.PostAsync 而不是 WebClient 通过 NameValueCollection 发布 Slack 消息

[英]Trying to Post a Slack Message through NameValueCollection using HttpClient.PostAsync instead of WebClient

我正在尝试使用 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);
}

我正在使用此代码尝试使用网络集成向 Slack 频道发布消息。 有没有办法在使用 HttpClient 时实现相同的功能?

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

在此先感谢您的帮助!

使用 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
                }
            }

当您在问题中标记 #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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM