2011-07-02 37 views
5

我一直在嘗試使用幾種不同的方法訪問Windows Phone上的基於REST的API,但我似乎遇到了將cookies附加到所有請求的問題。我試過WebClient方法(現在好像已經變成了標記SecurityCritical,所以你不能再繼承它並添加代碼)。我簡短地看了看HttpWebRequest,看起來很麻煩。無法使用RestSharp發送cookie

現在我正在使用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.

+0

你如何確定cookie不在請求中? –

+0

我已經將Fiddler作爲模擬器的代理運行,爲了確保我試圖將它指向只打印$ _COOKIE的PHP文件。 – NiteLite

+1

爲了繁榮,我會在這裏留下這個鏈接,以防其他人有同樣的問題。這似乎是RestSharp代碼的一個問題:http://groups.google.com/group/restsharp/browse_thread/thread/d93f73e9e300ba43 – NiteLite

回答

-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必須在您的實例引用要對其他請求被重用。

4

RestSharp 102.4似乎已經解決了這個問題。

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

,或者在你的情況

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

將正常工作。