9

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

4

3 回答 3

12

RestSharp 102.4 似乎已经解决了这个问题。

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

或者,在你的情况下

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

会正常工作。

于 2011-12-01T17:59:37.227 回答
1

我遇到了同样的问题,几个小时后我尝试了:

request.AddParameter()
request.AddHeader("Cookie", Cookie value);
and another ways, finnally the solution was using:
request.AddCookie(cookie name, cookie value);
request.AddCookie(cookie name, cookie value);      

我希望这可以解决问题。

于 2020-05-08T13:01:33.147 回答
-1

HttpWebRequest is the best to use. Simply user the CookieContainer to work with cookies. But you have to keep a reference of your CookieContainer over all your requests to get this work

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

cc must be referenced in your instance to be be reused on other request.

于 2011-11-09T21:22:17.460 回答