简体   繁体   English

使用 RestSharp 保存 cookie

[英]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.我正在尝试使用 RestSharp 在 WinPhone 7 Mango 的 RestClients 和应用程序会话之间获取一个 cookie。

If I use a single RestClient instance the cookie persists.如果我使用单个 RestClient 实例,则 cookie 会持续存在。 I want the cookie to last between RestClient instances and when a user returns to the app.我希望 cookie 在 RestClient 实例和用户返回应用程序之间持续存在。

RestSharp have recently added automatic cookie support! RestSharp 最近添加了自动 cookie 支持!

RestSharp 102.4+ supports using a shared System.Net.CookieContainer for all requests from the same IRestClient. RestSharp 102.4+ 支持对来自同一个 IRestClient 的所有请求使用共享的 System.Net.CookieContainer。 By doing so, any cookies set or unset in responses will be used in subsequent requests.通过这样做,响应中设置或取消设置的任何 cookie 都将在后续请求中使用。 In order to use a shared CookieContainer, simply set the property on your RestClient instance before using it:为了使用共享的 CookieContainer,只需在使用前设置 RestClient 实例的属性:

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

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

Cookie value must be encoded.必须对 Cookie 值进行编码。

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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