I have an issue - my http request to TFS always returns "401" status code.
Request code below:
public async Task TfsPostRequest(string url, string body, string username, string password)
{
using (var client = _httpClient.CreateClient("TfsClient"))
{
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
var content = new StringContent(body);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
request.Content = content;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
request.Headers.Authorization = new AuthenticationHeaderValue("Ntlm", Base64Encode(username, password));
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
...
}
catch (JsonException ex)
{
...
}
catch (Exception ex)
{
...
}
}
}
Base64Encode method:
public string Base64Encode(string username, string password)
{
string creds = string.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.Unicode.GetBytes(creds);
return Convert.ToBase64String(bytes);
}
HttpClient configuration code:
builder.Services.AddHttpClient("TfsClient", client => {
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client.DefaultRequestHeaders.Connection.Add("keep-alive");
});
When i try to execute simular one request using
credentialCache.Add(new Uri(uri), "Ntlm", validatingNetworkCredential);
with HttpWebRequest
it works correct.
My code will be executing with different user credentials and i want to use http client for that task instead of HttpWebRequest
. Is it possible?
HttpClientHandler
.