搜查官方文档后发现:
HttpWebRequest.AllowAutoRedirect Property (System.Net) | Microsoft Learn
微软提供的http类库HttpClient (HttpWebRequest\WebClient已不推荐使用,用HttpClient代替)有备注提醒:当使用自动重定向时,认证头会自动清除,目的是保证安全问题。至此问题清晰,找类库代替。
解决方案:
使用 Flurl库
string url = "http://127.0.0.1:8080/test/api";var response = url.WithHeader("Content-Type", "application/json").WithHeader("Authorization","Basic").WithSettings(s => s.Redirects.Enabled = true).WithSettings(s => s.Redirects.ForwardAuthorizationHeader = true).WithSettings(s => s.Redirects.ForwardHeaders = true).WithHeader("Expect", "100-continue").PutStringAsync(File.ReadAllText(filePath)).GetAwaiter().GetResult();
// Handle the response
Console.WriteLine(response.GetStringAsync().GetAwaiter().GetResult());