I am trying to make a GET api request with the below C# code but it fails with
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
at System.Net.WebClient.DownloadString(Uri address)
at System.Net.WebClient.DownloadString(String address)
at Rextester.Program.callAPI()
at Rextester.Program.Main(String[] args)
Note that the same API request works through postman.
private static void callAPI()
{
WebClient client = new WebClient();
client.UseDefaultCredentials = false;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
client.Headers.Add("Authorization", "Basic " + Base64Encode("<id:password>"));
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Environment-Id", "325");
client.QueryString.Add("query", "%7B%7D");
string reply = client.DownloadString("https://<server-api-url>");
Console.WriteLine(reply);
}
private static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
var encodedS = System.Convert.ToBase64String(plainTextBytes);
Console.WriteLine(encodedS);
return encodedS;
}
One more strange fact is that I see the exception printed before the encoded string. It should I think the other way round. The encoded string should be printed before since the method call happens before making the api call.