【问题标题】:c# httpclient authorize header not working for me?c# httpclient 授权标头对我不起作用?
【发布时间】:2019-10-14 13:29:15
【问题描述】:

我正在尝试制作一个可以让我从 discogs 查询数据库的应用程序。

根据Api documentation,我只需一个令牌就可以做到这一点。 所以我注册并获得了用户令牌。

现在当我将邮递员与https://api.discogs.com/database/search?release_title=nevermind&artist=nirvana&per_page=3&page=1&token=<my_user_token> 一起使用时 我收到了我期望的 json。

但是当我使用令牌在 c# 中创建 httpclient 时

    public string token = <my_user_token>;
    public static HttpClient client { get; set; }
    public static async Task InitilizeClient()
    {
        await GetAccesToken();
    }

    private static async Task GetAccesToken()
    {
        client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.BaseAddress = new Uri(@"https://api.discogs.com");
        //client.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Discogs", "token="+token);
        client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization","Discogs token=" + token);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

然后像这样使用客户端

    public static async Task QueryDataBaseAsync(string query)
    {
       if (query == null)
        {
            throw new Exception("query is empty");
        }
        string url = "";
        url = @"https://api.discogs.com/database/search?release_title="+query;
        if (client == null)
        {
            await InitilizeClient();
        }
        using (HttpResponseMessage response = await client.GetAsync(url))
        {
            if (response.IsSuccessStatusCode)
            {

            }
            else
            {
                throw new Exception(response.ReasonPhrase + " \n" + response.RequestMessage.ToString());
            }
        }

    }

然后我总是得到一个 ReasonPhrase "forbidden","statuscode: 403"

当我在HttpResponseMessage response 上设置断点时,我可以看到在“headers”=>“responsemessage”=>“headers”=>“authorization”下有我的令牌。

我做错了什么?

ps,抱歉英语不好,这不是我的母语

ps2,我是编程新手,如果你能 eli5 我做错了什么,我将不胜感激

【问题讨论】:

  • token 在哪里定义和初始化?此外,在工作 PostMan 请求中,它不是标头,而是查询字符串参数。
  • 公共字符串令牌在调用 InitilizeClient() 之前在我的构造函数中初始化;我将编辑原始问题以反映这一点
  • 最好的调试方法是使用像 fiddler 或 wireshark 这样的嗅探器来验证你的头文件是否正确。 Net Http 类使用不同的默认标头。供应商未指定的内容类型是浏览器兼容性。服务器可能需要 Chrome 兼容性,而您发送的是 IE 类型。 API 可能需要 SSL,而您使用的 SSL 加密版本错误。我将首先使用可以运行的供应商软件并与您的 c# 标头进行比较以验证差异。
  • 我有一个接近你想要做的答案。也许它可以帮助处理事件的顺序。 stackoverflow.com/questions/38494279/…

标签: c# json visual-studio api httpclient


【解决方案1】:

您可能需要在标题中提供用户代理。大致如下:

client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36");

像这样:

public class DiscConsumer
{
    //https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
    //curl "https://api.discogs.com/database/search?q=Nirvana" -H "Authorization: Discogs key=foo123, secret=bar456"

    private const string _urlQuery = "https://api.discogs.com/database/search?q={query}";
    private const string _key = "<....your key....>";
    private const string _secret = "<....your secret...>";

    private System.Net.Http.HttpClient _httpClient;
    public async Task InitilizeClient()
    {
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        var sslhandler = new HttpClientHandler()
        {
            //...in System.Security.Authentication.SslProtocols
            SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
        };
        _httpClient = new System.Net.Http.HttpClient(sslhandler);
        string authorization = $"Discogs key={_key}, secret={_secret}";
        _httpClient.DefaultRequestHeaders.Add("Authorization", authorization);
        _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36");
    }

    public async Task QueryDataBaseAsync(string query)
    {
        if (String.IsNullOrWhiteSpace( query ))
        {
            throw new Exception("query is empty");
        }
        string url = "";
        url = _urlQuery.Replace("{query}", query);
        if (_httpClient == null)
        {
            await InitilizeClient();
        }
        using (HttpResponseMessage response = await _httpClient.GetAsync(url))
        {
            if (response.IsSuccessStatusCode)
            {
                string s = await response.Content.ReadAsStringAsync();
                Console.WriteLine(s);
            }
            else
            {
                throw new Exception(response.ReasonPhrase + " \n" + response.RequestMessage.ToString());
            }
        }
    }
}

根据https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow,您可以在搜索的同时为每个请求提供密钥+秘密。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-24
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 2023-04-09
    • 2018-02-04
    • 1970-01-01
    相关资源
    最近更新 更多