调用web api时,C#不支持授权类型{ “ error “:“ unsupported _ grant _ type “ }

使用postman

image.png

image.png 使用代码,代码如下 { " 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"))
复制代码

这样就可以返回正确的结果了

image.png

猜你喜欢

转载自juejin.im/post/7096687871418957860
今日推荐