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

时间:2017-10-12 22:20:17

标签: azure-devops azure-devops-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

1 个答案:

答案 0 :(得分:1)

评论告诉您在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