C# httpclient 授权 header 对我不起作用?

标签 c# json visual-studio dotnet-httpclient

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

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

现在当我使用 postman https://api.discogs.com/database/search?release_title=nevermind&artist=nirvana&per_page=3&page=1&token=<my_user_token> 我收到了像我期望的那样的 JSON。

但是当我使用 token 在 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”下它有我的 token 。

我做错了什么?

PS。我是编程新手,所以如果您能解释我做错了什么,我将不胜感激

最佳答案

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

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,您可以在每个请求和搜索中提供 key + secret 。

关于C# httpclient 授权 header 对我不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58377892/

相关文章:

c++ - '类' : type parameter 'param' is incompatible with the declaration

c# - 如何以最快的方式处理 400K 数据的 foreach/group by?

c# - "protected"和 "virtual/override"之间的区别

python - 将 python 字典动态存储在 JSON 文件中

java - 如何验证 JSON 对象?

c++ - 如何使用 Visual Studio 2022(预览版 3)编译 Boost 库

javascript - 使用部分 View 将点击搜索转变为即时搜索

c# - 检测以太网线何时插入

javascript - Blogger 最近的帖子控制台错误 : Cannot read property 'title' of undefined

c# - 为代码覆盖关闭 Visual Studio 2010 中的 Lambda 表达式