【问题标题】:Is there a way to get only the access token using RestSharp? [duplicate]有没有办法使用 RestSharp 仅获取访问令牌? [复制]
【发布时间】:2021-12-22 04:34:26
【问题描述】:

我只想获取访问令牌并在新请求中传递它,但出现错误:IRestResponse does not contain a definition for "AccessToken'

var client = new RestClient("https://localhost:5001/");
client.Timeout = -1;
var ClientID = "client";
var ClientSecret = "secret";
var Scope = "Api1";
var request = new RestRequest("connect/token", Method.POST);
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", ClientID);
request.AddParameter("client_secret", ClientSecret);
request.AddParameter("scope", Scope);
IRestResponse response = client.Execute(request);
if (!response.IsSuccessful)
    {
       Console.WriteLine("Authorization token request failed with the following error: @{Error}", response.Content);
       throw new Exception(response.Content);
                           
    }
    else
    {
                                               
    var token = response.AccessToken;

....

【问题讨论】:

标签: c# .net restsharp


【解决方案1】:

试试这个

   var result = JsonConvert.DeserializeObject<dynamic>(response.Content); 
   var token = result.access_token //the name of the access token in your response can be different, change it to whatever suits your needs

【讨论】:

    【解决方案2】:

    我没有使用过 RestSharp,但查看了反序列化响应内容所需的文档。

    您可以使用 Execute() 版本执行此操作,该版本返回 IRestResponse,其中包含所请求对象的 T 数据成员。

    IRestResponse<TokenResponseClass> response = client.Execute<TokenResponseClass>(request);
    if (!response.IsSuccessful)
    {
       Console.WriteLine("Authorization token request failed with the following error: @{Error}", response.Content);
       throw new Exception(response.Content);
                           
    }
    else
    {
                                               
    var token = response.Data.AccessToken;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2012-12-29
      • 2020-03-02
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2016-10-18
      相关资源
      最近更新 更多