3

I'm new in API's world but I had a question, I want to get data from Web API but there's two authentication

  • First with proxy.
  • Second with API base authentication.

here's my Get Action code:

        HttpClientHandler handler = new HttpClientHandler();
        handler.Credentials = new NetworkCredential("test", "testing");
        HttpClient client = new HttpClient(handler);
        client.BaseAddress = new Uri("http://test.abctesting.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.
            MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
        var tenders = response.Content.ReadAsAsync<tenders>().Result;

this code work fine with me but just in pass over proxy username and password! How can I continue to Get API Data with authentication username and password?

2
  • Do you know which authentication mode your API is using? Commented Sep 18, 2017 at 20:05
  • Basic authentication I think Commented Sep 18, 2017 at 20:24

2 Answers 2

6

Since you mentioned "Basic Auth" on comments adding the following lines in addition to what you have might help

 var byteArray = Encoding.ASCII.GetBytes($"{yourUsername}:{yourPassword}");
 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

Although there are other popular modes of auth such as OAuth, Bearer etc. Change the key on AuthenticationHeaderValue according to the mode of authentication and set the value appropriately

Sign up to request clarification or add additional context in comments.

Comments

1

This should work:

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

string user = "user", password = "password";

string userAndPasswordToken =
    Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password));

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", 
    $"Basic {userAndPasswordToken}");

HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;

1 Comment

it got 3 errors .. .. unexpected charachter $ .. invalid expression term '' .. ) expected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.