简体   繁体   中英

Send Asp.net HttpClient Get result to browser

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 ???;
    }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM