调用web api时,C#不支持授权类型{ “ error “:“ unsupported _ grant _ type “ }
Posted 花开花落的个人博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了调用web api时,C#不支持授权类型{ “ error “:“ unsupported _ grant _ type “ }相关的知识,希望对你有一定的参考价值。
使用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"))
这样就可以返回正确的结果了
以上是关于调用web api时,C#不支持授权类型{ “ error “:“ unsupported _ grant _ type “ }的主要内容,如果未能解决你的问题,请参考以下文章
调用 Web API 2 端点时出现 HTTP 415 不支持的媒体类型错误
如何修复 grant_type 错误为 NULL - 使用 Pay Pal 的 REST API 访问令牌不受支持的授权类型
Web API Post 返回 415 - 不支持的媒体类型