HaydenThrash
HaydenThrash

Reputation: 107

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

I am trying to use HttpClient to post a NameValueCollection to a specific Url. I have the code working using WebClient, but I'm trying to figure out if it is possible to do using HttpClient.

Below, you will find my working code that uses 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);
}

I'm using this code to try to post a message to a Slack Channel using a web integration. Is there a way to implement this same functionality while using HttpClient?

The Slack error that I receive when I try to use HttpClient is "missing_text_or_fallback_or_attachment".

Thanks in advance for any help!

Upvotes: 2

Views: 2318

Answers (2)

Teoman shipahi
Teoman shipahi

Reputation: 23122

While you are tagging #slack in the question, I suggest you to use Slack.Webhooks nuget package.

Example usage I found is in here;

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);

Upvotes: 0

Mostafiz
Mostafiz

Reputation: 7352

Using 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
                }
            }

Upvotes: 0

Related Questions