1

I want to get only the access token and pass it in a new request, but I am getting an error: 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;

....

janw
  • 8,758
  • 11
  • 40
  • 62
Billy Dan
  • 29
  • 1
  • 8

2 Answers2

2

Try this

   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
XKZ
  • 126
  • 7
0

I haven't used RestSharp but looking at the docs you need to deserialize the response content.

You can do this using the Execute<T>() version which returns IRestResponse<T> which contains a T Data member of the requested object.

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;
bmiller
  • 1,454
  • 1
  • 14
  • 14