Friday, August 5, 2022

[FIXED] How can I get the Acces-token from Header with C#

Issue

I have a problem. I'd like to get the access-token from Header in my API. I am use this code below to access into my service. I am using C# and HttpClient.

static async Task Login()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://api.xxxxxx.com/auth/");
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("email", "xxx@localhost.com"),
                new KeyValuePair<string, string>("password", "hello123")
            });

            var result = await client.PostAsync("sign_in", content);
            string resultContent = await result.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
        }
    }

But, I am not able to get the access-token from header, someone here could help me with this issue ?

enter image description here


Solution

You need to access the HttpContent.Headers collection.

 var result = await client.PostAsync("sign_in", content);
 var token = result.Headers.GetValues("access-token").FirstOrDefault();


Answered By - John Wu
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.