【问题标题】:How can I use the access token to get a list of projects from a website in c#?如何使用访问令牌从 c# 中的网站获取项目列表?
【发布时间】:2017-12-09 13:51:06
【问题描述】:

我正在尝试创建一个 C# 控制台应用程序以从支持 REST OAuth 2.0 的网站下载项目详细信息。如何使用访问令牌向网站发出请求/响应调用? 这是我的代码:

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
    }

}

【问题讨论】:

  • 有什么问题?另外,如果客户端刚刚创建,为什么要取消挂起的请求?

标签: c# rest oauth-2.0


【解决方案1】:

您需要在请求中添加标头:

 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;
        }

【讨论】:

    猜你喜欢
    • 2018-03-17
    • 2012-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2018-01-13
    • 2012-09-22
    • 2020-02-26
    相关资源
    最近更新 更多