使用postman
使用代碼,代碼如下
{ " error ":" unsupported _ grant _ type " }
public static string GetToken(string url,string username ,string password)
{
GetTokenDto getTokenDto = new GetTokenDto() { Username = username,Password = password, grant_type = "password" };
//設定小駝峰模式,屬性名首字母小寫
var setting = new JsonSerializerSettings
{
ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
};
string jsonData = JsonConvert.SerializeObject(getTokenDto, setting);
var logger = SingleService.Services.GetService<ILogger>();
ServicePointManager.ServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate {
return true;
});//https請求 忽略證書,可以直接通路
using (HttpClient httpClient = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage())
{
using (HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/x-www-form-urlencoded"))
//using (HttpContent content = new StringContent(string.Format("grant_type=password&username={0}&password={1}",HttpUtility.UrlEncode(username),HttpUtility.UrlEncode(password)), Encoding.UTF8,"application/x-www-form-urlencoded"))
{
string contentType = content.Headers.ContentType.ToString();
request.RequestUri = new Uri(url);
request.Content = content;
request.Method = new HttpMethod("GET");
var result = httpClient.SendAsync(request).Result;
var str = result.Content.ReadAsStringAsync().Result;
logger.Info(typeof(DataSubHelper), str);
return str;
}
}
}
return url;
}
原因是什麼呢,原因是的預設實作
OAuthAuthorizationServerHandler
僅接受表單編碼(即
application/x-www-form-urlencoded
)而不是JSON編碼(
application/JSON
).
修改下代碼關鍵部分
using (HttpContent content = new StringContent(string.Format("grant_type=password&username={0}&password={1}",HttpUtility.UrlEncode(username),HttpUtility.UrlEncode(password)), Encoding.UTF8,"application/x-www-form-urlencoded"))