簡體   English   中英

如何在C#中使用基本身份驗證在github上創建一個要點

[英]How to create a gist on github with basic Authentication in C#

我使用C#.net 4.0,我想在github上用我的用戶名和密碼(使用基本身份驗證)創建一個公共要點。 http://developer.github.com/v3/auth/#basic-authentication

如果我使用正確的密碼,我得到響應: The remote server returned an error: (404) Not Found.

如果我使用了錯誤的密碼,我會收到回復: The remote server returned an error: (401) Unauthorized.

如何在用戶名下驗證和發布公開要點?

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM