为什么从C#发送后期请求时,我会从Slack收到“ not_authed”错误?

时间:2018-12-04 08:24:23

标签: c# json slack-api

我正在尝试将一个对象序列化为Json,然后将其发送到Slack。我已经成功完成了此操作而不进行序列化,而是使用了“字典”和“ 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看起来不错-它里面有令牌... 有人知道为什么吗?

1 个答案:

答案 0 :(得分:1)

所以,我想通了-我不应该将令牌放入要发送的JsonObject中。

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

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

然后它起作用。