Note: This is not a duplicate of this question. I have already read that question and its answers.
Approach 1
var client = new HttpClient() { BaseAddress = new Uri("https://myurl") };
var authenticationString = "username:password"; // Obviously this will be actual username & pass
var base64EncodedAuthenticationString = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(authenticationString));
client.DefaultRequestHeaders.Add("Basic", base64EncodedAuthenticationString);
HttpResponseMessage responseToken = client.GetAsync("/customer/151375").Result;
string data = responseToken.Content.ReadAsStringAsync().Result;
Above approach does not work and, if it helps, when I inspect the response.RequestMessage.RequestUri
it is different from https://myurl/customer/151375. This approach returns some HTML.
Approach 2
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Credentials = new NetworkCredential("username", "password")
};
var client = new HttpClient(httpClientHandler);
HttpResponseMessage response =
client.GetAsync("https://myurl/customer/151375/contacts").Result;
string data = response.Content.ReadAsStringAsync().Result;
Approach 2 works but Approach 1 does not work. To me both requests are the same but clearly they are not.
What are the differences between above 2 approaches?
Why does only Apporach 2 work?