无法使用 REST API 在 VSTS 中访问我的存储库

Can't access my repos in VSTS using REST API

我想访问我在 VSTS 中托管的存储库以及相应存储库中的每个分支。下面是我的代码

 public class VSTSController : ApiController
{
    const String c_collectionUri = "https://****.visualstudio.com/DefaultCollection";
    const String c_projectName = "****";
    const String c_repoName = "****";

    [HttpGet]
    [Route("api/VSTS/Init")]
    public string Init()
    {

        // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
        VssCredentials creds = new VssClientCredentials();
        creds.Storage = new VssClientCredentialStorage();

        // Connect to VSTS
        VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);

        // Get a GitHttpClient to talk to the Git endpoints
        GitHttpClient gitClient = connection.GetClient<GitHttpClient>();

        // Get data about a specific repository
        var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;
        return repo.RemoteUrl;
    }
}

当我运行这段代码时,我得到一个异常Microsoft.VisualStudio.Services.Common.VssUnauthorizedException' occurred in mscorlib.dll but was not handled in user code。 如何对 VSTS REST API 进行身份验证?我听不懂documentation.

该评论准确地告诉了您在 WebAPI 应用程序中实现此问题的原因:// Interactively ask the user for credentials, caching them so the user isn't constantly prompted

它无法以交互方式提示输入凭据,因此失败。

身份验证 documentation 提供了几个演示不同身份验证方法的示例。最简单的可能是个人访问令牌:

VssConnection connection = new VssConnection(new Uri(collectionUri), new VssBasicCredential(string.Empty, pat));

其中 pat 是一个包含有效个人身份验证令牌的变量。

但是,您可能希望最终实现 OAuth 身份验证,它已被详细记录并提供 sample code