R
R
Roman Rakzin2016-10-29 01:18:26
Computer networks
Roman Rakzin, 2016-10-29 01:18:26

How to read cookie in C# WebClient?

C# application downloading a file

string link = @"http://localhost:2613/siteapi/getfile"; 
WebClient webClient = new WebClient();
webClient.Headers.Add(HttpRequestHeader.Cookie, "accesscode=123456");
webClient.DownloadFileAsync(new Uri(link), @"c:\Download\" + "file.txt");

The server will respond with another cookie and return the file.
How can I read a cookie in a WebClient response?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rou1997, 2016-10-29
@Rou1997

No way, because you don’t work with the server’s response, the DownloadFileAsync method hides it from you, for full HTTP support, go to HttpWebRequest or RestSharp, by the way, the WebClient inside is also not ideal, it seems that the files didn’t download, but rewrote it to HttpWebRequest, and everything went.

#
#algooptimize #bottize, 2016-10-30
@user004

google webclient cookies
It is possible and quite easy.

A
Artem Voronov, 2016-10-30
@newross

This is easy to do with HttpClient using CookieContainer

var cookieContainer = new CookieContainer();
           _handler = new HttpClientHandler {CookieContainer = cookieContainer};
           _client = new HttpClient(_handler);

After authorization or any other request, you can save cookies
private void SaveCookie()
        {
            var cookies = _handler.CookieContainer.GetCookies(new Uri(BaseUrl));
            var cookie = cookies["PHPSESSID"];
            using (var writer = new StreamWriter(_cookieFile))
            {
                writer.Write(cookie.ToJson());
            }
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question