简体   繁体   中英

Saving a cookie with RestSharp

I am trying to get a cookie to persist between RestClients and app sessions for WinPhone 7 Mango using RestSharp.

If I use a single RestClient instance the cookie persists. I want the cookie to last between RestClient instances and when a user returns to the app.

RestSharp have recently added automatic cookie support!

RestSharp 102.4+ supports using a shared System.Net.CookieContainer for all requests from the same IRestClient. By doing so, any cookies set or unset in responses will be used in subsequent requests. In order to use a shared CookieContainer, simply set the property on your RestClient instance before using it:

var client = new RestClient ("http://server/");
client.CookieContainer = new System.Net.CookieContainer();

Documentation: https://github.com/restsharp/RestSharp/wiki/Cookies

Cookie value must be encoded.

if ( header["Set-Cookie"] != null )
{
string value = header["Set-Cookie"];

Encoding iso = Encoding.GetEncoding("iso-8859-9");//may be utf-8

value = HttpUtility.UrlEncode(value, iso);
Cookie moCookie = new Cookie( "Cookie", value);
moCookie.Domain = GatewayURI.Trim();
CookieContainer CommCookie = new CookieContainer();
CommCookie.Add( moCookie );
request.CookieContainer = CommCookie;
}

您需要手动保存 cookie 信息,RestSharp 中不支持在会话之间保存 cookie。

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