WebClient GET 请求因 401 未授权而失败

WebClient GET Request Fails With 401 Unauthorized

我正在尝试使用以下 C# 代码发出 GET api 请求,但失败并显示

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)

请注意,相同的 API 请求通过 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;
}

一个更奇怪的事实是我看到编码字符串之前打印的异常。我应该反过来想。应该在之前打印编码字符串,因为方法调用发生在 api 调用之前。

从@Panagiotis Kanavos 那里得到一些指导后,我跟踪了来自 Fiddler 的 api 调用,并了解到 api 调用正在被重定向(http 状态代码 - 307)。 C# 客户端默认配置为不通过重定向授权 header。因此我得到了 401 Unauthorized 错误。 这是 fixed 通过添加对 401 状态代码的检查并重新发送具有授权 header 的 api 请求。

感谢@Panagiotis Kanavos 的帮助