Search code examples
c#jsonhttppostget

C#: HTTP Post with Authentication issue


I'm trying to learn how to work with a REST API. Unfortunately the one i'm using requires authentication and I can't get my code right. Anyone willing to help me get my code straight?

 using System;
    using System.Text;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using System.Collections.Generic;

    namespace HttpClientAuth
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                var userName = "admin";
                var passwd = "adminpw";
                var url = "http://10.10.102.109/api/v1/routing/windows/Window1";

                using var client = new HttpClient();

                var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(authToken));

                var result = await client.GetAsync(url);

                var requestContent = new HttpRequestMessage(HttpMethod.Post, url);

                //Request Body in Key Value Pair
                requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    ["CanYCentre"] = "540",
                    ["CanXCentre"] = "960",
                });

                var content = await result.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
        }
    }

Solution

  • Seems you are confused how you could make a POST request. You could try below snippet.

             ApiRequestModel _requestModel = new ApiRequestModel();
    
            _requestModel.RequestParam1 = "YourValue";
            _requestModel.RequestParam2= "YourValue";
    
    
            var jsonContent = JsonConvert.SerializeObject(_requestModel);
            var authKey = "c4b3d4a2-ba24-46f5-9ad7-ccb4e7980da6";
            var requestURI = "http://10.10.102.109/api/v1/routing/windows/Window1";
            using (var client = new HttpClient())
            using (var request = new HttpRequestMessage())
            {
                request.Method = HttpMethod.Post;
                request.RequestUri = new Uri(requestURI);
                request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                request.Headers.Add("Authorization", "Basic" + authKey);
    
                var response = await client.SendAsync(request);
    
    
                //Check status code and retrive response
    
                if (response.IsSuccessStatusCode)
                {
    
                    dynamic objResponse = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());
                }
                else
                {
                    dynamic result_string = await response.Content.ReadAsStringAsync();
                }
    
            }
    

    Update: As per your given screenshot on comment you could also try this way.

    private async Task<string> HttpRequest()
        {
            //Your Request End Point
            string requestUrl = $"http://10.10.102.109/api/v1/routing/windows/Window1";
            var requestContent = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    
            //Request Body in Key Value Pair
            requestContent.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["CanYCentre"] = "540",
                ["CanXCentre"] = "960",
            });
    
            requestContent.Headers.Add("Authorization", "Basic" + "YourAuthKey");
    
            HttpClient client = new HttpClient();
            //Sending request to endpoint
            var tokenResponse = await client.SendAsync(requestContent);
            //Receiving Response
            dynamic json = await tokenResponse.Content.ReadAsStringAsync();
            dynamic response = JsonConvert.DeserializeObject<dynamic>(json);
    
            return response;
        }
    

    Update 2:

    If you still don't understand or don't know how you would implement it Just copy and paste below code snippet.
    
    
      private static async Task<string> HttpRequest()
            {
    
                object[] body = new object[] 
                {
                    new { CanYCentre = "540" },
                    new { CanYCentre = "960" }
                };
                var requestBody = JsonConvert.SerializeObject(body);
    
                using (var client = new HttpClient())
                using (var request = new HttpRequestMessage())
                {
                    request.Method = HttpMethod.Post;
                    request.RequestUri = new Uri("http://10.10.102.109/api/v1/routing/windows/Window1");
                    request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                    request.Headers.Add("Authorization", "Basic" + "YourAuthKey");
    
                    var response = await client.SendAsync(request);
                    var responseBody = await response.Content.ReadAsStringAsync();
    
                    dynamic result = JsonConvert.DeserializeObject<dynamic>(responseBody);
                    return result;
                }
    
            }
    

    Hope this would help you. If you encounter any problem feel free to share.