public static async Task<Tuple<bool, string>> GetTokenForAccess(this User user)
{
var scheme = HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://";
string baseAddress = $"{scheme}{HttpContext.Current.Request.Url.Authority}";
using (var client = new HttpClient())
{
var accept = "application/json";
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "*/*");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
string grant_type = "password";
string body = $"grant_type={grant_type}&username={user.PhoneNumber}&password={user.Password}&grant_access=true";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{baseAddress}/token")
{
Content = new StringContent(body,
Encoding.UTF8,
"application/x-www-form-urlencoded")
};
var response = await client.SendAsync(request);
var token = response.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
if (string.IsNullOrEmpty(token.Error))
{
return new Tuple<bool, string>(true, token.AccessToken);
}
else
{
return new Tuple<bool, string>(false, token.Error);
}
}
}
答案 0 :(得分:0)
您的问题应该在这里:
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
删除“ application / json”,因为OAuthAuthorizationServerHandler的默认实现仅接受表单编码(即application / x-www-form-urlencoded),而不接受JSON编码(application / JSON)。