使用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"))
这样就可以返回正确的结果了
|