1

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.

1 Answer 1

4

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();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Just like that! Thank you Andy... Much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.