从httpclient响应中获取access_token的值应该是这样的:

huangapple go评论73阅读模式
英文:

How do I grab access_token value from the httpclient reponse?

问题

var responseJson = await response.Content.ReadAsStringAsync();
var responseObject = JsonSerializer.Deserialize<Dictionary<string, string>>(responseJson);
var bearToken = responseObject["access_token"];

这段代码将从响应中提取 "access_token" 的值存储在变量 bearToken 中。

英文:

I have a C# method a calling service to retrieve the access_token, how do I pull that value from response returned?

try {
            var client = new HttpClient();
            client.BaseAddress = new Uri(_serviceConfig.DataGapsBaseUrl);
            var request = new HttpRequestMessage(HttpMethod.Post, &quot;/dataopssecurity/oauth2/token&quot;);

            var formData = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
            formData.Add(new KeyValuePair&lt;string, string&gt;(&quot;grant_type&quot;, _serviceConfig.grantType));
            formData.Add(new KeyValuePair&lt;string, string&gt;(&quot;username&quot;, _serviceConfig.username));
            formData.Add(new KeyValuePair&lt;string, string&gt;(&quot;password&quot;, _serviceConfig.password));
            formData.Add(new KeyValuePair&lt;string, string&gt;(&quot;scope&quot;, _serviceConfig.scope));

            request.Content = new FormUrlEncodedContent(formData);
            var authenticationString = $&quot;{Username}:{Password}&quot;;
            request.Headers.Authorization = new AuthenticationHeaderValue(
            scheme: &quot;Basic&quot;,
            parameter: Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(authenticationString)));
            //client.DefaultRequestHeaders.Add($&quot;Authorization&quot;, $&quot;Basic {Convert.ToBase64String($&quot;{Username}:{Password}&quot;)}&quot;);
            var response = await client.SendAsync(request);

How do I something like var bearToken = Response["access_token"] ?

Json Returned:

{
    &quot;access_token&quot;: &quot;eyJraWQiOiIxNDA2ZGQ3MC0zOWQ4LTRjOGItYjI1Mi0yM2RhZjk0Mjg0NTMiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJjZGlzcG9sbGluZ3N2YyIsImF1ZCI6ImRhdGFvcHNzdWl0ZS1jbGktY2xpZW50IiwidXNlci1hdXRob3JpdGllcyI6WyJ2aWV3LXRlb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lsib3BlbmlkIl0sImlzcyI6Imh0dHA6XC9cLzEwLjIzNy4wLjQ6NjA1NVwvZGF0YW9wc3NlY3VyaXR5IiwiZXhwIjoxNjgwMjc2NjI2LCJpYXQiOjE2ODAxOTAyMjZ9.SKhyBhRAgMkgdS5PbZ3xg6NBu5Kk0NSpYakcYJUfEPbf9GE8gTPCv1iJFQWJd5qxMbcL6DFs-2jP8SQ8UvJ6MiVFsTw5e09zspNgeV77Q_1dGgkghNHxU8r164eDI6Cp9GtTLFpwyAgW4o9HBE0A7jXk7w_vGJVEEpT-Wl7WpyHDCXBPOb2_yxIfLH1qhA00SrORTt555DPLM1ZkpRf1njeBTHRNVahReD5r3Bigp1pxWftFBFPoNMDhTpZrFqMQ1reKsmZOKUoOHCi2AtEDPEAzPwYS31i-R8Rd4wbZE3moJtj9SPN70YgT1yngt-HT4zYSaIfxG1wodhSAz5Izrw&quot;,
    &quot;refresh_token&quot;: &quot;KJSh8AkLmdOPxD2nzMAyeDel4Dai7UxWiftS4wUxjNw_LjGvuQK5dj2cTKgWLjeRkxzkLoQKmng5iLpUMSKVrZ_lzGSPHeedaAI6GBdKcraLzKdm7t69hA1q6jVvLGn7&quot;,
    &quot;scope&quot;: &quot;openid&quot;,
    &quot;token_type&quot;: &quot;Bearer&quot;,
    &quot;expires_in&quot;: 86400
}

答案1

得分: 2

Possible solution is to deserialize the response into an object and read the property of the object.

string content = !response.IsSuccessStatusCode
    ? null
    : response.Content.ReadAsStringAsync().Result;

TokenResponse tokenResponse = JsonConvert.DeserializeObject<TokenResponse>(content);
string accessToken = tokenResponse.access_token;

The 'TokenResponse' object can be as simple as an object with just the 'access_token' property.

As an alternative you can use Json.net or the MS Json libraries to read the value from the Json.

英文:

Possible solution is to deserialize the response into an object and read the property of the object.

string content = !response.IsSuccessStatusCode
       ? null
       : response.Content.ReadAsStringAsync().Result;

TokenResponse tokenResponse = JsonConvert.DeserializeObject&lt;TokenResponse&gt;(content);
string accessToken = tokenResponse.access_token;

The 'TokenResponse' object can be as simple as an object with just the 'access_token' property.

As an alternative you can use Json.net or the MS Json libraries to read the value from the Json.

huangapple
  • 本文由 发表于 2023年3月31日 02:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定