Search code examples
c#.net-coredotnet-httpclientwebapi

how to add header to GetAsync in httpclient


I have to convert a ps project to C# and I am not familiar with the operation of accessing webapi in C# Below is the code in PS that has been working like a charm.

PowerShell Code:

$api_key = [myKey]
$header = @{"x-api-key"=$api_key}
$uri = [myURI]
$resp = invoke-webrequest -uri $uri -method get -headers 

In C#, I use HttpClient and GetAsync method to retrieve the resource. My issue is I am not sure how to insert the header which contains my apiKey to the site.

My code is:

private static HttpClient _httpClient = new HttpClient();
var response = await _httpClient.GetAsync([myURI]);

Because the request does not contain my key, I got 401 error (unauthorized operation). I know what was wrong but I do not know how to fix it. I do not see anywhere in GetAsync that allows a header. Maybe I should use a different method?

Basically, I would like to convert the PS snippet above to C# .netcore.

Please advise.


Solution

  • You should use the HttpRequestMessage pattern to do this. For example:

    using (var msg = new HttpRequestMessage(HttpMethod.Get, fromUri))
    {
        msg.Headers.Add("x-header-test", "the value");
        using (var resp = await _client.SendAsync(msg))
        {
            resp.EnsureSuccessStatusCode();
            return await resp.Content.ReadAsStringAsync();
        }
    }