How can I use the access token to get a list of pr

2019-09-23 07:37发布

问题:

I am trying to create a C# console application to download project details from a website which supports REST OAuth 2.0. How do I make a request/response call to the website using the Access Token? Here is my code:

public string token = "4bjskfa2-b37d-6244-8413-3358b18c91b6";

public async Task GetProjectsAsync()
{
    try
    {
        HttpClient client = new HttpClient();
        var projects = "https://app.rakenapp.com/api/v2/projects?" + token;  

        client.CancelPendingRequests();
        HttpResponseMessage output = await client.GetAsync(projects);

        if (output.IsSuccessStatusCode)
        {
            string response = await output.Content.ReadAsStringAsync();
            project proj = JsonConvert.DeserializeObject<project>(response);

            if (proj != null)
            {
                Console.WriteLine(proj.name); // You will get the projects here.
            }
        }
    }
    catch (Exception ex)
    {
        //catching the exception
    }

}

回答1:

you need to add a header to your request:

 string url = "https://app.rakenapp.com/api/v2/projects";
 using (var httpClient = new HttpClient())
       {
           httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authorizationToken);
           HttpResponseMessage response = await httpClient.GetAsync(url);
           var contents = await response.Content.ReadAsStringAsync();
           var model = JsonConvert.DeserializeObject<project>.contents); 
           return model;
        }