【发布时间】:2018-02-25 17:09:15
【问题描述】:
我正在开发一个项目,该项目从前端客户端接收访问令牌并使用该访问令牌我必须向 Twitter API 发出请求,以获取用户详细信息,包括电子邮件地址和个人资料图片网址.
对于 Facebook,这只是一个普通的获取请求,对于 Google 和 Microsoft,我只需在 Header 中添加访问令牌作为 Bearer 令牌,但是,我无法为 Twitter 找到方法。
这是我必须提出请求的网址。
https://api.twitter.com/1.1/account/verify_credentials.json
这是 Facebook、Google 和 Microsoft 的代码。
private async Task<Profile> ProfileAsync(string token,string providerName)
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if((providerName=="Google") || (providerName=="Microsoft"))
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
var formatters = new List<MediaTypeFormatter>()
{
new JsonMediaTypeFormatter()
};
string url;
Profile profile = null;
if (providerName=="Facebook")
{
url = $"https://graph.facebook.com/me?fields=id,name,email&access_token={token}";
}
else if(providerName=="Google")
{
url = $"https://www.googleapis.com/userinfo/v2/me";
}
else if(providerName=="Microsoft")
{
url = $"https://graph.microsoft.com/v1.0/me/";
}
else
{
throw new Exception("Unsupported grant type.");
}
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
profile = await response.Content.ReadAsAsync<Profile>(formatters);
}
if(providerName=="Microsoft")
{
profile.email = profile.userPrincipalName;
profile.name = profile.displayName;
}
return profile;
}
}
【问题讨论】:
标签: c# asp.net twitter asp.net-core