401从c#console app连接到github API时出错

时间:2013-11-03 23:36:44

标签: c# http authentication github-api

晚上好。

对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;
    }
}

非常感谢你有时间看这个。我敢肯定我已经忘记了什么,但我只是不知道是什么。

Welshboy

1 个答案:

答案 0 :(得分:2)

如果你添加如下认证头:

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();