无法通过RestSharp发送cookie

问题描述 投票:7回答:3

我一直在尝试使用几种不同的方法在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);
    });
}

[如果有人对为什么未将Cookie发送到服务器有任何提示,请让我知道:)我正在使用RestSharp 101.3和.Net 4。

c# .net windows-phone-7 restsharp
3个回答
8
投票

RestSharp 102.4似乎已解决此问题。

 request.AddParameter(_cookie_name, _cookie_value, ParameterType.Cookie);

或您的情况

request.AddParameter(this.gallerySessionIdKey, this.sessionId, ParameterType.Cookie);

将正常工作。


0
投票

我有同样的问题,几个小时后我尝试了:request.AddParameter()request.AddHeader(“ Cookie”,Cookie值);最后,解决方案使用的是:request.AddCookie(cookie名称,cookie值);request.AddCookie(cookie名称,cookie值);

我希望可以解决问题。


-1
投票

HttpWebRequest是最好的用法。只需使用CookieContainer即可使用Cookie。但是您必须在所有请求中保留CookieContainer的引用才能获得此工作]

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

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

© www.soinside.com 2019 - 2024. All rights reserved.