简体   繁体   中英

HttpClient with PostAsync code optimisation

I am using below code, Code is working fine. I am new to HTTPClient so i am not sure if this code is optimised properly or what is the best way to code it. I found this example which talks about deadlock even though it is about parallel programing but i just want to make sure ifthis code can be improved/optimized for performance or error.

I connect to website with certain key parameter & get in return json data. which ii process for further action.

protected void btnClient_Click(object sender, EventArgs e)
    {
        using (var client = new HttpClient())
        {

            client.BaseAddress = new Uri("https://secure.telr.com/");
            client.DefaultRequestHeaders.ExpectContinue = false;
            var result = client.PostAsync("gateway/order.json",
                new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("ivp_method", "create"),
                new KeyValuePair<string, string>("ivp_store", "12345"),
                new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
                new KeyValuePair<string, string>("ivp_cart", "123452"),
                new KeyValuePair<string, string>("ivp_desc", "Descripion"),
                new KeyValuePair<string, string>("ivp_test", "1"),
                new KeyValuePair<string, string>("ivp_amount", "10.00"),
                new KeyValuePair<string, string>("ivp_currency", "UAD"),
                new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
                new KeyValuePair<string, string>("ivp_framed", "1"),
            })).Result;


            var jsonData = (JObject)JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            dynamic jObj = JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);

            string url = jsonData["order"]["url"].ToString();
            Response.Write("<br>url" + url + "<br>");

            ltrTelr.Text = "<iframe id= 'telr' src='" + url + "' ></iframe>";

        }
    }

You should avoid trying to access the Task.Result when you're not sure if/when your API is going to return data. That would block your thread because it's trying to evaluate the result.

Instead, when you're calling an async method you should use the 'await' keyword so you free up the thread, like this:

protected async Task btnClient_Click(object sender, EventArgs e)
{
    using (var client = new HttpClient())
    {

        client.BaseAddress = new Uri("https://secure.telr.com/");
        client.DefaultRequestHeaders.ExpectContinue = false;
        var result = await client.PostAsync("gateway/order.json",
            new FormUrlEncodedContent(new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("ivp_method", "create"),
            new KeyValuePair<string, string>("ivp_store", "12345"),
            new KeyValuePair<string, string>("ivp_authkey", "xxx-xxxxxx"),
            new KeyValuePair<string, string>("ivp_cart", "123452"),
            new KeyValuePair<string, string>("ivp_desc", "Descripion"),
            new KeyValuePair<string, string>("ivp_test", "1"),
            new KeyValuePair<string, string>("ivp_amount", "10.00"),
            new KeyValuePair<string, string>("ivp_currency", "UAD"),
            new KeyValuePair<string, string>("return_auth", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("return_can", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("return_decl", "http://localhost:1044/Test2.aspx"),
            new KeyValuePair<string, string>("ivp_framed", "1"),
        }));

        var rawData = await result.Content.ReadAsStringAsync();

        var jsonData = (JObject)JsonConvert.DeserializeObject(rawData);
        dynamic jObj = JsonConvert.DeserializeObject(rawData);

        string url = jsonData["order"]["url"].ToString();
        Response.Write("<br>url" + url + "<br>");

        ltrTelr.Text = "<iframe id= 'telr' src='" + url + "' ></iframe>";

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM