1
I have this script in c# that makes me recover a token from an external api to mine that I am developing. Until then, I managed to recover without problems the parameters of this api (the token is within these parameters) however I only need the token and not the other parameters q it is passing me. How do I recover/filter token only ?
Attached below is the script I developed and what was returned to me by the api (what is between the red boxes are the parameters I don’t need).
public async Task<string> GetToken()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.json");
var config = builder.Build();
var username = config.GetSection("SindiOnibus:username").Value;
var password = config.GetSection("SindiOnibus:password").Value;
_Url = config.GetSection("SindiOnibus:Url").Value;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
HttpResponseMessage respToken = await client.PostAsync(
_Url, formContent);
return await respToken.Content.ReadAsStringAsync();
}
}
Where do I retrieve the token:
string token = await GetToken();
Client.DefaultRequestHeaders.Add("Authorizarion", $"Bearer {token}");
"{\r\n \"access_token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IkdPTkVUIiwianRpIjoiYzA1ZjBhYTgtZWY5Yy00ZTg5LTkzZWYtMjAzNTU2Nzk0YzFkIiwiaWF0IjoxNTczNDkyMzQzLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL3JvbGUiOiJHT05FVCIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWUiOiJHT05FVCIsImV4cCI6MTU3MzQ5MjQwMywiaXNzIjoiSXNzdWVyIiwiYXVkIjoiQXVkaWVuY2UifQ.nykUMmCgN4GiDY2yuagt_mls8Qs9N8HfFD3h30M5lyc\",\r\n \"expires\": \"2019-11-11T14:13:23.2756-03:00\",\r\n \"usuario\": {\r\n \"id\": **,\r\n \"nome\": \"****\"\r\n }\r\n}"
You can create a class with all these properties to deserialize your string. And after deserialized you can take any property value.
– Maycon F. Castro