【问题标题】:How to authorize HttpClient for TFS如何为 TFS 授权 HttpClient
【发布时间】:2018-06-06 17:52:41
【问题描述】:

我在尝试访问 TFS 中的提交时收到了以下输出: uri 在我的浏览器中有效,但身份验证不适用于我的 httpClient。我的用户名是域\用户,现在我只使用用户名的用户部分,但我已经尝试过使用和不使用域。请帮忙!

System.Net.Http.HttpRequestException:响应状态码不表示成功:401(未授权)。 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

try 
{ 
    var httpClient = new HttpClient();

    var byteArray = Encoding.ASCII.GetBytes("username:password");

    httpClient.DefaultRequestHeaders.Authorization
                        = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));


    var response = await httpClient.GetStringAsync(uri);
    Console.WriteLine(response);
}
catch (Exception ex)
{
    Console.WriteLine(ex.ToString());
}

【问题讨论】:

    标签: authentication tfs httpclient


    【解决方案1】:

    如果您使用的是 Windows 身份验证并且您已使用正确的帐户登录,则无需提供身份验证标头。

    而不是var httpClient = new HttpClient();,写

    var httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

    【讨论】:

      【解决方案2】:

      只需尝试用以下格式替换var byteArray = Encoding.ASCII.GetBytes("username:password");(它适用于我):

      var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "domain\\username", "pasword"));
      

      示例:

      using System;
      using System.Net.Http;
      using System.Net.Http.Headers;
      using System.Text;
      using System.Threading.Tasks;
      
      namespace GetCommits
      {
          class Program
          {
              public static void Main()
              {
                  Task t = GetCommits();
                  Task.WaitAll(new Task[] { t });
              }
              private static async Task GetCommits()
              {
                  try
                  {
                      var httpClient = new HttpClient();
      
                      var byteArray = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "domain\\username", "password"));
      
                      httpClient.DefaultRequestHeaders.Authorization
                                          = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
      
      
                      var response = await httpClient.GetStringAsync("http://ictfs2015:8080/tfs/DefaultCollection/Git-Scrum/_apis/git/repositories/389e8215-1fb2-4fdc-bd04-ebc8a8a4410e/commits/a395accfe2f1ed60ee404d6515fc9f55631cbe42");
                      Console.WriteLine(response);
                  }
                  catch (Exception ex)
                  {
                      Console.WriteLine(ex.ToString());
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-09
        • 1970-01-01
        • 2019-07-05
        • 1970-01-01
        • 2013-01-15
        • 2018-05-25
        相关资源
        最近更新 更多