Reputation: 5670
I have an asp.net mvc controller method "Index" as showed below. I want to use HttpClient GetAsync method to get a response from wwww.google.com and then send this response as the response to browser, so browser shows www.google.com. But I do not know how to replace response with the response I got from client.GetAsync. Please help! I don't want to use redirect though.
public async Task<ActionResult> Index()
{
HttpClient client = new HttpClient();
var httpMessage = await client.GetAsync("http://www.google.com");
return ???;
}
Upvotes: 1
Views: 4098
Reputation: 922
please try to see this post HttpClient Request like browser
response.EnsureSuccessStatusCode();
using (var responseStream = await response.Content.ReadAsStreamAsync())
using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(decompressedStream))
{
return streamReader.ReadToEnd();
}
I make sample on my machine
full action here
public async Task<string> Index()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
var httpMessage = await client.GetAsync("http://www.google.com");
httpMessage.EnsureSuccessStatusCode();
using (var responseStream = await httpMessage.Content.ReadAsStreamAsync())
using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(decompressedStream))
{
return streamReader.ReadToEnd();
}
// return View();
}
example for get cookie from server
Upvotes: 1
Reputation: 218862
You can read the response from the http call as a string using the ReadAsStringAsync()
method and return that string back as the response from your action method.
public async Task<ActionResult> Index()
{
HttpClient client = new HttpClient();
var httpMessage = await client.GetAsync("http://www.google.com");
var r = await httpMessage.Content.ReadAsStringAsync();
return Content(r);
}
The above code will return you the content of google.com when you access the Index
action.
Upvotes: 2