C#可以编写但不能读取存储库的BitBucket API

C#可以编写但不能读取存储库的BitBucket API,c#,webclient,bitbucket-api,C#,Webclient,Bitbucket Api,我正在尝试使用C#访问BitBucket API。我可以做一些动作,但不能做其他动作。值得注意的是,写入存储库是可行的,但读取存储库却不行 using System.Net; using System.Collections.Specialized; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // TLS v1.2 only var client = new WebClient() { Cred

我正在尝试使用C#访问BitBucket API。我可以做一些动作,但不能做其他动作。值得注意的是,写入存储库是可行的,但读取存储库却不行

using System.Net;
using System.Collections.Specialized;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; // TLS v1.2 only
var client = new WebClient()
{
    Credentials = new NetworkCredential("user", "app_password"),
    BaseAddress = "https://api.bitbucket.org",
};

client.DownloadString(
    "/2.0/repositories/friendly_private_account/repo");     // 403 Forbidden
client.DownloadString(
    "/2.0/repositories/friendly_private_account/repo/src"); // 403 Forbidden
client.UploadValues(
    "/2.0/repositories/friendly_private_account/repo/src",
    new NameValueCollection() {
        { "/bb.txt", "here is\nsome content\n" },
        { "message", "Commit from API, called with C# WebClient" },
    });                                                     // Creates a commit! What!?
这有点奇怪,因为如果在创建应用程序密码时启用了
写入
权限,则会自动获得
读取
权限

DownloadString()
也没有问题。如果应用程序密码具有
webhook
权限,则可以读取Web hook

client.DownloadString(
    "/2.0/repositories/friendly_private_account/repo/hooks");
// {"pagelen": 10, "values": [{ … }]}
有趣的是,
curl
对于相同的凭证没有任何问题

$curl--user“${user}:${app\u password}”\
--url“https://api.bitbucket.org/2.0/repositories/friendly_private_account/repo"
#{“scm”:“git”,“网站”:“has_wiki”:false,}

使用
--verbose
运行
curl
,实际上会返回描述您的凭据拥有哪些权限以及需要哪些权限的标题。在上面的示例中,它需要
repository
,我有
repository:write
。它并没有说我有
repository:read
,但是请求还是成功的。

听起来像
WebClient
只发送
授权

也许BitBucket在一些未经身份验证的端点上响应401,激发
WebClient
以身份验证重新发送请求;但对其他人返回403,立即结束请求

显式添加
授权
标题可以解决问题,尽管有点难看

using System.Net;
using System.Collections.Specialized;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;  // TLS v1.2 only
var client = new WebClient()
{
    // Credentials = new NetworkCredential("user", "app_password"), // Take this line out
    BaseAddress = "https://api.bitbucket.org",
};

client.Headers[HttpRequestHeader.Authorization] =
    "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("user:app_password"));

client.DownloadString(
    "/2.0/repositories/friendly_private_account/repo");             // Now it works

真奇怪,你会写但不会读。无论如何,不是100%确定,这可能是安全协议问题。如果尚未启用TLS 1.1和/或TLS 1.2,请尝试启用。System.Net.ServicePointManager.SecurityProtocol |=SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;我还建议添加UserAgentI,我尝试过使用TLS v1.2显式地添加,没有任何更改。将User Agent设置为
curl/7.54.0
也没有帮助。