none
convert javascript post call to web API into C# code RRS feed

  • Question

  • Hi,

    Can anybody help me converting this Js code in C#(like a HttpClient PostAsync or something)?

    let aircraftResult = await fetch(`${host}/api/v0/rpc/resource.aircraft.get`, {
            method: "post",
            headers: {
                "authorization": `Bearer ${token.access_token}`,
                "content-type": "application/json",
            },
            body: JSON.stringify({
                params: {}
            })
        });
        let aircrafts = await aircraftResult.json();

    Thank you!

    Thursday, September 27, 2018 3:47 PM

All replies

  • Hi,

    try this:

            public async Task<T> HttpJsonRequestAsync<T>(string access_token, string host)
            {
                var task = new Task<T>(() =>
                {
                    using (var client = new WebClient())
                    {
    
                        var values = new WebHeaderCollection();
                        values["authorization"] = $"Bearer {access_token}";
                        values["content-type"] = "application/json";
                        client.Headers = values;
                        var serializer = new JavaScriptSerializer();
                        using (var stream = client.OpenRead($"{host}/api/v0/rpc/resource.aircraft.get"))
                        {
                            using (var reader = new StreamReader(stream))
                                return serializer.Deserialize<T>(reader.ReadToEnd());
                        }
                    }
                });
                task.Start();
                return await task;
            }

    Greetings, Chris



    • Edited by DerChris88 Thursday, September 27, 2018 9:33 PM
    Thursday, September 27, 2018 4:17 PM
  • I forgot to post the json :O. Just add this string to the request: "{\"params\":[]}"

    Greetings, Chris

    Thursday, September 27, 2018 5:44 PM
  • Here is the new code:

    public async Task<T> HttpJsonRequestAsync<T>(string access_token, string host)
    {
        var task = new Task<T>(() =>
        {
            using (var client = new WebClient())
            {
    
                var values = new WebHeaderCollection();
                values["authorization"] = $"Bearer {access_token}";
                values["content-type"] = "application/json";
                client.Headers = values;
                var serializer = new JavaScriptSerializer();
                byte[] response = client.UploadData($"{host}/api/v0/rpc/resource.aircraft.get", Encoding.UTF8.GetBytes("{\"params\":[]}"));
                return serializer.Deserialize<T>(client.Encoding.GetString(response));
            }
        });
        task.Start();
        return await task;
    }

    You can use it like this:

    var json = await HttpJsonRequestAsync<dynamic>("access_token", "host");

    Greetings, Chris

    Thursday, September 27, 2018 9:43 PM
  • Hi LaurentiuNeacsu,

    Here is another sample code for your reference.

    class Test
            {
    
                public void RunHttpTest()
                {
                    Task t = new Task(TryConnect);
                    t.Start();
                    Console.WriteLine("Connecting to NS...");
                    Console.ReadLine();
                }
    
                private static async void TryConnect()
                {
                    
                    String jsonString = JsonConvert.SerializeObject(
                        new NewObj() { }
                    );
    
    
    string url  = $"{host}/api/v0/rpc/resource.aircraft.get";
     var uri     = new Uri(@url);
     HttpClient c = new HttpClient();
     c.BaseAddress = uri;
    c.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{token.access_token}");
    
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, url);
    req.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
    
    HttpResponseMessage httpResponseMessage = await c.SendAsync(req);
                    httpResponseMessage.EnsureSuccessStatusCode();
    ttpContent httpContent = httpResponseMessage.Content;
    
    string responseString = await httpContent.ReadAsStringAsync();
    
                    Console.WriteLine(responseString);
                }
            }
    
            class NewObj
            {
                public string Name { get; set; }
                public string Email { get; set; }
            }


    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, September 28, 2018 5:44 AM
    Moderator
  • Hi,

    clientsecret = "htf3..."

    Is this your private key for the api? That's dangerous to leak it here.

    You should remove the keys from your post and get a new one. After that we take care of your problem.

    Greetings, Chris

    Friday, September 28, 2018 8:25 PM