c# - 从 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 看起来不错 - 它里面有令牌......有人知道为什么吗?
解决方案
所以,我想通了——我不会把我的令牌放在我想发送的 JsonObject 中。
在这种情况下(使用httpclient
)的解决方案是必须为客户端添加一个用于授权的标头,如下所示:
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "lé token");
然后它就起作用了。
推荐阅读
- javascript - 多按钮点击事件
- python-2.7 - 使用 Python 的 dns.update 进行动态 DNS 更新,返回 rcode REFUSED
- angular - 将代码从 ChangeDetectionStrategy.Default 重构为 ChangeDetectionStrategy.OnPush
- postgresql - json 类型的 Postgres 无效输入语法详细信息:令牌“%”无效
- sorting - 在 Vala 中对默认数组进行排序的简单方法
- apache - 如何自动检测强制门户
- python - 具有自定义值权重的 pandas 中的虚拟编码
- terraform - 指定模块时,terraform init 不起作用
- javascript - Java有join方法,NodeJs有什么节点相当于它?
- python - 将第二个参数传递给 pool.map 中的函数