具有PostAsync代码优化的HttpClient

时间:2017-01-19 04:34:08

标签: c# asp.net optimization dotnet-httpclient

我使用下面的代码,代码工作正常。我是HTTPClient的新手,所以我不确定这段代码是否正确优化或者编码的最佳方式是什么。我发现这个例子讨论了死锁,即使它是关于并行编程的,但我只是想确保这个代码是否可以针对性能或错误进行改进/优化。

我使用某些关键参数连接到网站&得到json数据。我正在处理进一步的行动。

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

        }
    }

1 个答案:

答案 0 :(得分:2)

当您不确定API何时/何时将返回数据时,您应该避免尝试访问Task.Result。这会阻止你的线程,因为它试图评估结果。

相反,当您调用异步方法时,您应该使用等待&#39;等等。关键字让你释放线程,如下所示:

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

    }
}