我在尝试访问TFS中的提交时收到了此输出: uri在我的浏览器中工作,但身份验证不适用于我的httpClient。我的用户名是domain \ user,现在我只使用用户名的用户部分,但我已尝试使用和不使用域名。请帮忙!
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());
}
答案 0 :(得分:0)
如果您使用的是Windows身份验证,并且已使用正确的帐户登录,则无需提供身份验证标头。
而不是var httpClient = new HttpClient();
,写
var httpClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
答案 1 :(得分:0)
尝试使用以下格式替换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());
}
}
}
}