You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AuthenticationHeaderValue与NetworkCredential的区别及两种认证方法差异原因

注:此问题并非其他类似问题的重复,我已阅读过相关问题及其答案。

方法1

var client = new HttpClient() { BaseAddress = new Uri("https://myurl") };
var authenticationString = "username:password"; // Obviously this will be actual username & pass
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Add("Basic", base64EncodedAuthenticationString);
HttpResponseMessage responseToken = client.GetAsync("/customer/151375").Result;
string data = responseToken.Content.ReadAsStringAsync().Result;

上述方法无法生效,经检查,response.RequestMessage.RequestUri与预期的https://myurl/customer/151375不符,返回内容为HTML。

方法2

HttpClientHandler httpClientHandler = new HttpClientHandler()
{
    Credentials = new NetworkCredential("username", "password")
};

var client = new HttpClient(httpClientHandler);
HttpResponseMessage response =
client.GetAsync("https://myurl/customer/151375/contacts").Result;
string data = response.Content.ReadAsStringAsync().Result;

方法2可正常生效,但方法1不行。我原本认为两种请求是一致的,但显然并非如此。请问这两种方法有何区别?为何仅方法2有效?


内容的提问来源于stack exchange,提问作者CodingYoshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:10:20