阅读从httpclient.sendasync返回的内容

时间:2018-11-22 10:30:06

标签: string get return asp.net-core-mvc dotnet-httpclient

我有此代码:

private static readonly HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();

using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://someurl.com"))
{
    requestMessage.Headers.Add("sessionId", "ABC123");
    delayresponse = client.SendAsync(requestMessage).Result;
}

我尝试了其他几种方法,但均未成功。我的目的是向MVC控制器发出GET请求,然后使用Content读取该控制器返回的HttpClient。返回的Contentstring。此代码有什么问题?

1 个答案:

答案 0 :(得分:0)

要访问string的结果,您可以像这样从Content阅读:

        HttpClient client = new HttpClient();
        using (var request = new HttpRequestMessage(HttpMethod.Get, @"http://localhost/IISWindows/home/test"))
        {
            var response = client.SendAsync(request).Result;
            var content = response.Content.ReadAsStringAsync().Result;
        }

以另一种方式,您可以尝试GetStringAsync

            var result = client.GetStringAsync(@"http://localhost/IISWindows/home/test").Result;