Heron Dantas
Heron Dantas

Reputation: 167

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

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", "[email protected]"),
                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

Upvotes: 1

Views: 27517

Answers (2)

Farhan Rafi
Farhan Rafi

Reputation: 21

You can get easily by following code:

static async Task Login([FromHeader] string headerToken)

But to get this headerToken, variable name should be same in header also. headerToken example

Upvotes: 2

John Wu
John Wu

Reputation: 52240

You need to access the HttpContent.Headers collection.

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

Upvotes: 3

Related Questions