我有此代码:
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
。返回的Content
是string
。此代码有什么问题?
答案 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;