1

I am creating the ASP.NET which is calling a third party Rest API. The third party API can be accessed only giving username and password. Also uses Http Basic Authentication

 public string Get(string LabName)
   {
    string userName = ConfigurationManager.AppSettings["username"];
    string password = ConfigurationManager.AppSettings["password"];
    string BaseURL = ConfigurationManager.AppSettings["BaseURL"];

    using (var client = new HttpClient())
    {

        Uri uri = new Uri(BaseURL);
        client.BaseAddress = uri;
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
        string clarity_URL = BaseURL+"api/v2/labs?name="+LabName;
        var response = client.GetAsync(clarity_URL).Result;

        string responseString = response.Content.ReadAsStringAsync().Result;
        return responseString;

Should I be using HttpClient or HttpWebRequest.I am not sure how to pass the username and password while calling the Rest API in the ASP.NET.Can anyone suggest me how to securely call the API

1 Answer 1

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

client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
Sign up to request clarification or add additional context in comments.

3 Comments

Since I have the String userName tried giving var byteArray = Encoding.ASCII.GetBytes(userName:password); it throws error like Error 1 The best overload for 'GetBytes' does not have a parameter named 'userName'
You should go like Encoding.ASCII.GetBytes(username+":"+password);
@user4912134 if you think this answer was the right solution, kindly mark it as answered. :)

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.