简体   繁体   中英

How do you make a Get request to api with Bearer token and use the response data with C# (Windows Server)?

I need to receive data from an API via C# on a windows server. I have been able to receive my access token with the help of Luis Quintanilla's Spotify code https://gist.github.com/lqdev/5e82a5c856fcf0818e0b5e002deb0c28 .

One thing I can't figure out is how to use this token in a Get Request using a Bearer token header. This is what I have so far.

Console.WriteLine("Token API");
AccessToken token = GetToken().Result;
Console.WriteLine(String.Format("Access Token: {0}", token.access_token));

        
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token);

        List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
        requestData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));

        FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);

        var request =  client.GetAsync("https://theapiendpoint.com", requestBody);
        // var response = request;
        var response = request.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<AccessToken>(response);

I'm C# illiterate and the above produces some errors, specifically around the GetAsync request. I don't think I can add a header via the body like above. It is also erroring out on the request.Content piece. So how would one make this type of call and use the returned data? Is it "better" to make an async function and use the return? If so how do you pass the token down to said function? Again I'm VERY new to C# please be gentle. My Thanks in advance.

NET Core and .NET 5+

The second parameter of client.GetAsync is not the request body: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getasync?view=net-6.0

You can send a GET request with a body (which doesn't seem normal) using client.SendAsync . You build your HttpRequestMessage first.

    List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
    requestData.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = new Uri("https://theapiendpoint.com"),
        Content = new FormUrlEncodedContent(requestData)
    };

    var responseMessage = await client.SendAsync(request);
    responseMessage.EnsureSuccessStatusCode();
    var responseString = await responseMessage.Content.ReadAsStringAsync();

Also check what version of .NET you are using. There are different reccommended ways to new HTTPClient : https://docs.microsoft.com/en-us/dotnet/fundamentals/networking/httpclient-guidelines

Edit:

Last 3 lines as Non-Async:

var responseMessage = client.Send(request);
responseMessage.EnsureSuccessStatusCode();
var responseString = responseMessage.Content.ReadAsStringAsync().Result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM