我正在尝试用 C# 向 slack 通道发送消息。通过 http 请求,使用 Webhook url。 在获取响应行中,我收到 400- 错误请求。
我的功能:
public void SendSlackAlert(string message, string slackUrl)
{
try
{
var content = $"{{\r\n\"text\":\"{Context}\r\n{message} \"\r\n}}";
if (string.IsNullOrWhiteSpace(slackUrl))
{
return;
}
var httpRequest = WebRequest.Create(slackUrl) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Timeout = Convert.ToInt32(TimeSpan.FromDays(1).TotalMilliseconds);
var bytesToSend = Encoding.UTF8.GetBytes(content);
httpRequest.ContentType = "application/json;charset=utf-8";
httpRequest.ContentLength = bytesToSend.Length;
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(bytesToSend, 0, bytesToSend.Length);
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var responseReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
// return "Error";
}
}
我被转移到捕获错误,在这一行中:
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
非常感谢任何帮助的尝试。
谢谢!
我在其他地方看到,设置编码可能会导致 Slack API 出现问题。
不要将 Content-Type 标头与编码一起设置,而是尝试仅将 Content-Type 标头设置为应用程序 JSON。
替换此行:
httpRequest.ContentType = "application/json;charset=utf-8";
用这行:
httpRequest.Headers.Add(HttpRequestHeader.ContentType, "application/json");
我参加聚会有点晚了,但这个问题仍然需要一个解决方案,因为几乎没有什么可以帮助的。我的猜测是您的有效负载 JSON 格式错误。
作为参考,这里有一个适用于简单明文消息的基本实现。您还可以扩展序列化器以处理更复杂的对象和 Slack 的上下文块。
public void SendMessage(string message, string channelWebhook)
{
try
{
var payload = new
{
text = message
};
var serialisedPayload = JsonConvert.SerializeObject(payload);
var httpClient = new HttpClient();
var response = httpClient.PostAsync(channelWebhook, new StringContent(serialisedPayload, Encoding.UTF8, "application/json")).Result;
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to send slack message");
}
}