大家晚上好
我对 C# 有点陌生,但我正在玩 github api,我正在努力了解一些基本的身份验证。我写了一个控制台应用程序,其唯一目的是链接 github 站点并从那里拉下我的个人资料。当我调用不需要身份验证的电话时,它工作正常。
但是,如果我尝试使用基本身份验证进行身份验证,我会收到 401 错误,即使我输入了正确的用户名和密码。我用谷歌搜索了一下,看起来我的代码是正确的,但我不明白为什么我没有被授权。
我附上了下面的代码,所有使用的东西都存在且正确。
class gitHubConnection : ConnectionManager
{
public override string getRepositories()
{
string web_response = null;
try
{
CredentialCache cache = new CredentialCache();
NetworkCredential nc = new NetworkCredential("githubUsername", "githubPassword");
cache.Add(new Uri("https://api.github.com/user"), "Basic", nc);
WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Credentials = nc;
WebResponse response = request.GetResponse();
web_response = response.ToString();
}
catch (UriFormatException e)
{
Console.WriteLine("rats!!!!" + e.StackTrace);
}
catch (IOException ioe)
{
Console.WriteLine("something went pop " + ioe.StackTrace);
}
return web_response;
}
}
非常感谢您抽出宝贵时间查看此内容。我确定我忘记了什么,但我只是不知道是什么。
威尔士男孩
最佳答案
如果您像这样添加身份验证 header ,它会起作用:
WebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/user");
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes("user:password")));
WebResponse response = request.GetResponse();
关于c# - 从 C# 控制台应用程序连接到 github API 时出现 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19759570/