无法使用RestSharp发送cookie

Nit*_*ite 7 .net c# windows-phone-7 restsharp

我一直试图使用几种不同的方法在Windows Phone上访问基于REST的API,但我似乎遇到了将cookie附加到请求中的问题.我已经尝试过这种WebClient方法(现在似乎已经标记为SecurityCritical,因此您不能再继承它并添加代码).我简要地看了一下HttpWebRequest,看起来很麻烦.

现在我正在使用RestSharp,它似乎可以使用,但我仍然遇到问题,我的cookie没有被添加到请求发送时.

我的代码如下:

// ... some additional support vars ...
private RestClient client;

public ClassName() {
    client = new RestClient();
    client.BaseUrl = this.baseAddress.Scheme + "://" + baseAddress.DnsSafeHost;
}

public void GetAlbumList()
{
    Debug.WriteLine("Init GetAlbumList()");

    if (this.previousAuthToken == null || this.previousAuthToken.Length == 0) 
    {
        throw new MissingAuthTokenException();
    }

    RestRequest request = new RestRequest(this.baseUrl, Method.GET);

    // Debug prints the correct key and value, but it doesnt seem to be included
    // when I run the request
    Debug.WriteLine("Adding cookie [" + this.gallerySessionIdKey + "] = [" + this.sessionId + "]");
    request.AddParameter(this.gallerySessionIdKey, this.sessionId, ParameterType.Cookie);

    request.AddParameter("g2_controller", "remote:GalleryRemote", ParameterType.GetOrPost);
    request.AddParameter("g2_form[cmd]", "fetch-albums-prune", ParameterType.GetOrPost);
    request.AddParameter("g2_form[protocol_version]", "2.2", ParameterType.GetOrPost);
    request.AddParameter("g2_authToken", this.previousAuthToken, ParameterType.GetOrPost);

    // Tried adding a no-cache header in case there was some funky caching going on
    request.AddHeader("cache-control", "no-cache");

    client.ExecuteAsync(request, (response) =>
    {
        parseResponse(response);
    });
}
Run Code Online (Sandbox Code Playgroud)

如果有人有任何关于为什么没有将cookie发送到服务器的提示,请告诉我:)我正在使用RestSharp 101.3和.Net 4.

Sat*_*hat 6

RestSharp 102.4似乎解决了这个问题.

 request.AddParameter(_cookie_name, _cookie_value, ParameterType.Cookie);
Run Code Online (Sandbox Code Playgroud)

或者,在你的情况下

request.AddParameter(this.gallerySessionIdKey, this.sessionId, ParameterType.Cookie);
Run Code Online (Sandbox Code Playgroud)

会很好的.


Mor*_*rti -1

HttpWebRequest 是最好用的。只需使用 CookieContainer 即可处理 cookie。但是你必须在你的所有请求中保留 CookieContainer 的引用才能完成这项工作

CookieContainer cc = new CookieContainer();
HttpWebRequest webRequest = HttpWebRequest.CreateHttp(uri);
webRequest.CookieContainer = cc;
webRequest.BeginGetResponse((callback)=>{//Code on callback},webRequest);
Run Code Online (Sandbox Code Playgroud)

cc 必须在您的实例中引用才能在其他请求中重用。