1

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);
            }
        }
    }
1
  • Hey try Update 2 just copy and paste. on your code base ^^ Commented Feb 27, 2020 at 9:51

2 Answers 2

2

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.

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

8 Comments

You could try with your local host request would send, are you sure your request is alright as per your server requirement ?
Yeah I've seen , Updated the answer if its work for you. Let me know your update.
ha ha that's silly man make your method static because your main method is static and remember non static field cannot be instantiated inside static field just try private static async Task<string> HttpRequest()
Like this format is universal requestContent.Headers.Add("Authorization", "Basic" + "YourAuthKey");
Ok like above? I still need to deal with the NotImplememntedExeption. Any hint on that?
|
1

For those looking for an alternative version of a C# Http JSON PUT with Authentication:

using System;
using System.Text;
using System.Net;
using System.IO;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            //URL
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");

            //Basic Authentication
            string authInfo = "admin" + ":" + "adminpw";
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;

            //Application Type
            httpWebRequest.ContentType = "application/json";

            //Method
            httpWebRequest.Method = "PUT";

            // JSON Body
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"ID\":\"1\"," +
                              "\"Phone\":\"1234567890\"}";

                streamWriter.Write(json);
                Console.WriteLine("PUT Body: " + json);
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
            }

            //Status Code
            Console.WriteLine("URL: " + httpWebRequest.RequestUri);
            Console.WriteLine("Status Discription " + httpResponse.StatusDescription);

            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Status code " +(int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
            }
            else 
            {
                Console.WriteLine("Status code " + (int)httpResponse.StatusCode + " " + httpResponse.StatusCode);
            }
            // Close the response.
            httpResponse.Close();
        }
    }
}

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.