1

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;
        }

    }

1 Answer 1

2

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));
  
Sign up to request clarification or add additional context in comments.

Comments

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.