如何使用HttpWebRequest.Credentials属性进行基本身份验证?

Jos*_*nke 4 .net c# authentication

如何使用Webrequest Credentials属性发送基本身份验证标头?即使PreAuthenticate设置为true,为什么Authorization标头不会随请求一起发送?

WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Credentials = new NetworkCredential("githubUsername", "githubPassword");
request.PreAuthenticate = true;
var response = request.GetResponse();
Run Code Online (Sandbox Code Playgroud)

Jos*_*nke 5

服务器应发送包含 WWW-Authenticate HTTP标头的HTTP 401 Not Authorized响应代码.

WWW-Authenticate: Basic realm="example"
Run Code Online (Sandbox Code Playgroud)

PreAuthenticate属性仅在进行身份验证后才有效.来自MSDN:

如果在进行身份验证后发送带有请求的HTTP Authorization标头,则为true;否则为true.否则,错误.默认值为false.

有关详细信息,请参阅其他答案.