c# - 如何使用 C# 中的基本身份验证在 github 上创建要点

标签 c# github github-api gist

我使用 C# .net 4.0,我想在 github 上用我的用户名和密码(使用基本身份验证)创建一个公共(public)要点。 http://developer.github.com/v3/auth/#basic-authentication

如果我使用正确的密码,我会得到响应:远程服务器返回错误:(404) 未找到。

如果我使用了错误的密码,我会得到响应:远程服务器返回了一个错误:(401) Unauthorized。

如何使用我的用户名验证和发布公共(public)要点?

http://developer.github.com/v3/gists/#create-a-gist .我尝试发送的 json:

{
    "description": "the description for this gist",
    "public": true,
    "files": {
        "file1.txt": {
            "content": "my new content "
        }
    }
}

C#.NET 4.0 代码

private void button_createGist_Click(object sender, EventArgs e)
    {
        String jsonMessage = "{ \"description\": \"the description for this gist\",  \"public\": true,"
                   + "\"files\": {   \"file1.txt\": {"
                   + "\"content\":\"my new content \"  } }}";

        String _url = "https://api.github.com/gists/";

        HttpWebRequest req = WebRequest.Create(new Uri(_url)) as HttpWebRequest;

        String userName = "myUserName";
        String userPassword = "pass123";  
        string authInfo = userName + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

        req.Method = "POST";
        req.ContentType = "application/json";
        // req.Headers.Add(string.Format("Authorization: token {0}", oauthToken));
         //req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(username + ":" + password)));
        req.Headers.Add("Authorization", "Basic " + authInfo);
        StreamWriter writer = new StreamWriter(req.GetRequestStream());

        System.Diagnostics.Debug.WriteLine(jsonMessage);
        writer.Write(jsonMessage);
        writer.Close();

        string result = null;
        using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)//Exception here
        {
            StreamReader reader =
                new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
            System.Diagnostics.Debug.WriteLine(result);
        }
    }

最佳答案

我会把完整的例子放在网上。如果您在问题中发布的示例应该有效 改变

String _url = "https://api.github.com/gists/";

String _url = "https://api.github.com/gists";

使用/gists代替/gists/

关于c# - 如何使用 C# 中的基本身份验证在 github 上创建要点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18960868/

相关文章:

c# - 使用 Twilio(或任何其他提供商)在短信中伪造来电显示

c# - MVC Url 请求 - 路径中的非法字符

c# - 如何在 C# 中使用窗口窗体创建动态下拉列表

GitHub pull 请求显示已经在目标分支中的提交

github - 如何将 Octopress 博客部署到现有的 gh-pages 静态站点?

c# - Asp.Net Core v1.1 从同一解决方案中的另一个项目获取继承的类名

git - 像 gitignore 但不是 git ignore

ruby - 拒绝任何包含某些文件之外的更改的原始推送

github - 如何以编程方式识别 fork 的 github 存储库?

github - 我无法通过 github 搜索 api 过滤问题