【问题标题】:Performing XML Request with HttpClient in .NET 4.5 +在 .NET 4.5 + 中使用 HttpClient 执行 XML 请求
【发布时间】:2017-03-21 14:35:21
【问题描述】:

我编写了以下代码来使用 .NET 的 HttpWebClient 库执行 XML 请求,如下所示:

 public async Task<string> DoRequest()
        {

            using (var httpClient = new HttpClient())
            {
                string requestXML = "My xml here...";
                var request = new HttpRequestMessage(HttpMethod.Post, "example.com");
                request.Content = new StringContent(requestXML, Encoding.UTF8, "text/xml");
                var response = await httpClient.SendAsync(request);
                return await response.Content.ReadAsStringAsync();
            }
        }

并且在控制台应用程序的主要功能中:

 Klijent test= new Klijent();
 var res = test.DoRequest();

但是 res 返回类型总是向我显示:

Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

我如何使用这个库实际执行请求?我在这里做错了什么??

【问题讨论】:

    标签: c# asp.net xml console-application dotnet-httpclient


    【解决方案1】:

    等待结果

    var res = test.DoRequest().Result;
    

    您期望立即得到结果,即使您的代码是异步的。

    【讨论】:

    • 啊,就是这样...... Ty 这么多:) :)
    • 或使用res= await test.DoRequest();。您只需要在不能使用async 的方法中使用.Result,例如控制台应用程序的Main 方法
    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    相关资源
    最近更新 更多