Best way to save cookie in C# .NET?
Sometimes, you may need to call a 'login' url, passing in some sort of username/password. The web service will then usually return a cookie that you may use in subsequent requests.
In the following code(C# .NET), what is the correct way to save this cookie?
cookies = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
cookies = req.CookieContainer; //*choice 1*
cookies.Add(req.CookieCo开发者_JS百科ntainer.GetCookies(uri)); //*choice 2*
cookies.Add(response.Cookies); //*choice 3*
}
With choice 1, there doesn't seem to be a way to 'append' the returned CookieContainer to an existing CookieContainer (if I am saving other cookies).
you should pass your existing cookie container to the server, it will return it back plus whatever changes it did. That's normal behavior of web servers - they rarely clean up cookies.
i.e. first create cookie container, init whatever you want in it, then pass it to HttpWebResponse. Rinse, repeat.
精彩评论