Home > Enterprise >  C# Call RestAPI with basic Authentication
C# Call RestAPI with basic Authentication

Time:10-07

I am new to RestAPI and am not sure how to call one and pass it credentials. I have a Windows Forms with a "POST" button. This project is built using .Net framework 4.5. When user clicks on this button it executes code with the class below. In this calls there is a Post method that calls a RestAPI. This RestApi requires basic authentication. Any help would be great.

 public static class CallRestAPI
    {
        private static readonly string baseURL = "https://servername/fscmRestApi/resources/11.13.18.05/erpintegrations";
        
        
        public static async Task<string> Post(string name, string job)
        {
            var inputData = new Dictionary<string, string>
            {
                {"name", name },
                {"job", job }
            };

            var input = new FormUrlEncodedContent(inputData);
            using (HttpClient client = new HttpClient())
            {

                using (HttpResponseMessage res = await client.PostAsync(baseURL   "users", input))
                {
                    using (HttpContent content = res.Content)
                    {
                        string data = await content.ReadAsStringAsync();
                        if (data != null)
                        {
                            return data;
                        }
                    }


                }



            }

            return string.Empty;
        }

    }

CodePudding user response:

You have to add the authorization header:

 var byteArray = Encoding.ASCII.GetBytes($"{UserName}:{Password}");

 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
  
  • Related