我正在尝试实现与Asana API兼容的Xamarin应用。
我已经成功实现了Asana文档here中记录的OAuth ...至少我认为它是成功的。我从HTTP状态为“ OK”的HTTPResponse中的令牌端点获取访问令牌。
[但是当我转过身,尝试使用相同的访问令牌进行API调用时,出现403禁止错误。我在浏览器中尝试了相同的API调用(登录到Asana后),并且运行良好,这使我相信我确实可以访问该资源,因此对我的请求授权必定存在问题。] >
有问题的API调用是(documented here):https://app.asana.com/api/1.0/workspaces。
我的C#代码如下(缩写为相关部分,并假定ACCESS_TOKEN
包含我从令牌交换端点获得的访问令牌):
HttpClient client = new HttpClient(); client.BaseAddress = "https://app.asana.com/api/1.0"; client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ACCESS_TOKEN); client.DefaultRequestHeaders.Add("Accept", "application/json");
然后我在以下功能中使用此
HttpClient
(命名为client
):
// Returns a list of the Asana workspace names for the logged in user.
private async Task<List<string>> GetWorkspacesAsync()
{
List<string> namesList = new List<string>();
// Send the HTTP Request and get a response.
this.UpdateToken(); // Refreshes the token if needed using the refresh token.
using (HttpResponseMessage response = await client.GetAsync("/workspaces"))
{
// Handle a bad (not ok) response.
if (response.StatusCode != HttpStatusCode.OK)
{
// !!!THIS KEEPS TRIGGERING WITH response.StatusCode AS 403 Forbidden!!!
// Set up a stream reader to read the response.
// This is for TESTING ONLY
using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
// Extract the json object from the response.
string content = reader.ReadToEnd();
Debug.WriteLine(content);
}
throw new HttpRequestException("Bad HTTP Response was returned.");
}
// If execution reaches this point, the Http Response returned with code OK.
// Set up a stream reader to read the response.
using (StreamReader reader = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
// Extract the json object from the response.
string content = reader.ReadToEnd();
JsonValue responseJson = JsonValue.Parse(content);
foreach (JsonValue workspaceJson in responseJson["data"])
{
string workspaceName = workspaceJson["name"];
Debug.WriteLine("Workspace Name: " + workspaceName);
namesList.Add(workspaceName);
}
}
}
// I have other awaited interactions with app storage in here, hence the need for the function to be async.
return namesList;
}
我正在尝试实现与Asana API兼容的Xamarin应用。我已经成功实现了Asana文档中记录的OAuth,至少我认为它是成功的。我...
最后找到答案。看来我没有正确使用HttpClient
;一个微妙的事物,应该是等效的,但不是由于实现方式而定。