首页 > 解决方案 > 从 c# 发送后请求时,为什么我会从 Slack 收到“not_authed”错误?

问题描述

我正在尝试将一个对象序列化为 Json,然后将其发送给 Slack。我在没有序列化的情况下成功地做到了这一点,而是使用“Dictionary”和“FormUrlEncodedContent”然后发送它。但是现在,为了让事情变得更容易和更敏捷,我只想创建一个可以序列化的 JSon 类,然后将其用于我想要发送的每个请求。

这是我的代码:

我的 JsonObject:

    public class JsonObject
    {
        private string _token = "xoxp-MyToken";
        [JsonProperty("token")]
        public string token { get { return _token; } }
        [JsonProperty("channel")]
        public string channel { get; set; }
        [JsonProperty("as_user")]
        public bool as_user = true;      
        [JsonProperty("username")]
        public string username { get;set; } 
        [JsonProperty("text")]
        public string text { get; set; }
}

我的客户:

public class BpsHttpClient
{
    private readonly HttpClient _httpClient = new HttpClient { };
    public Uri UriMethod { get; set; }

    public BpsHttpClient(string webhookUrl)
    {
        UriMethod = new Uri(webhookUrl);
    }        

    public async Task<HttpResponseMessage> UploadFileAsync(StringContent requestContent)
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UriMethod);
        request.Content = requestContent;
        var response = await _httpClient.SendAsync(request);

        return response;
    }
}

主要的:

 class MainArea
    {
        public static void Main( string[] args)
        {
            try
            {
                Task.WaitAll(SendMessage());
            }
            catch(Exception ass)
            {
                Console.WriteLine(ass);
                Console.ReadKey();
            }
        }
        private static async Task SendMessage()
        {
            var client = new BpsHttpClient("https://slack.com/api/chat.postMessage");
            JsonObject JO = new JsonObject();
            JO.channel = "DCW21NBHD";
            JO.text = "This is so much fun :D !";
            var Json = JsonConvert.SerializeObject(JO, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

            var StringJson = new StringContent(Json, Encoding.UTF8, "application/json");
            var DeSon = JsonConvert.DeserializeObject(Json);

            Console.WriteLine(DeSon); //this is for me to see if my JsonObject looks correct - it does ;)
            Console.ReadKey();

            var Response = await client.UploadFileAsync(StringJson);

            string AnswerContent = await Response.Content.ReadAsStringAsync();

            Console.WriteLine(AnswerContent);
            Console.ReadKey();
        }

}

当我运行代码时,我总是得到答案:

输出:
{"ok":false,"error":"not_authed"}

虽然我认为我的 JsonObject 看起来不错 - 它里面有令牌......有人知道为什么吗?

标签: c#jsonslack-api

解决方案


所以,我想通了——我不会把我的令牌放在我想发送的 JsonObject 中。

在这种情况下(使用httpclient)的解决方案是必须为客户端添加一个用于授权的标头,如下所示:

httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "lé token");

然后它就起作用了。


推荐阅读