401 Unauthorized - C#

Hello,

Can some one please help me with resolving the issue which I’m struggling to crack for 2 days? I keep on getting the unauthorized error using this code. I tried different things but ended with frustration.

            string authKey = "API_KEY";
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(authKey);
            var authKeyBase64String = System.Convert.ToBase64String(plainTextBytes);

            var url = new Uri("https://api.company-information.service.gov.uk/search/companies");
            var parameters = "?q=microsoft";
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = url;
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authKeyBase64String);
                HttpResponseMessage httpResponse = await httpClient.GetAsync(parameters);
                if (httpResponse.IsSuccessStatusCode)
                {
                    var content = httpResponse.Content.ReadAsStringAsync().Result;
                    if (content != null)
                    {
                        Console.WriteLine(content);
                    }
                }
            }

This would be a great help for me.

Please use the search facility on this site for ‘unauthorized’ and read the posts and answers. It explains everything.
I think your first problem though is the missing ‘:’ at the end of your API_KEY …

1 Like

Thanks MarkWilliams.

I found my issue as I was using the TEST environment API key instead of PROD. I created a new key and its working now.