HttpWebRequest and Set-Cookie header in response not parsed (WP7)

后端 未结 4 642
借酒劲吻你
借酒劲吻你 2021-01-06 02:41

I am trying to get the header \"Set-Cookie\" or access the cookie container, but the Set-Cookie header is not available. The cookie is in the response header, but it\'s not

相关标签:
4条回答
  • 2021-01-06 02:55

    Is the cookie httponly? If so, you won't be able to see it, but if you use the same CookieContainer for your second request, the request will contain the cookie, even though your program won't be able to see it.

    0 讨论(0)
  • 2021-01-06 02:57

    You must edit the headers collection directly. Something like this:

    request.Headers["Set-Cookie"] = "name=value";
    
    request.BeginGetResponse(myCallback, request);
    
    0 讨论(0)
  • 2021-01-06 03:01

    Try explicitly passing a new CookieContainer:

    CookieContainer container = new CookieContainer();
    container.Add(new Uri("http://yoursite"), new Cookie("name", "value"));
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://yoursite");
    request.CookieContainer = container;
    request.BeginGetResponse(new AsyncCallback(GetData), request);
    
    0 讨论(0)
  • 2021-01-06 03:08

    You are receiving HttpOnly cookies:

    Set-Cookie: _CWFServer_session=[This is the session data]; path=/; HttpOnly 
    

    For security reasons, those cookies can't be accessed from code, but you still can use them in your next calls to HttpWebRequest. More on this here : Reading HttpOnly Cookies from Headers of HttpWebResponse in Windows Phone

    With WP7.1, I also had problems reading non HttpOnly cookies. I found out that they are not available if the response of the HttpWebRequest comes from the cache. Making the query unique with a random number solved the cache problem :

    // The Request
    Random random = new Random();  
    // UniqueQuery is used to defeat the cache system that destroys the cookie.
    _uniqueQuery = "http://my-site.somewhere?someparameters=XXX"
           + ";test="+ random.Next();
    
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_uniqueQuery);
    request.BeginGetResponse(Response_Completed, request);
    

    Once you get the response, you can fetch the cookie from the response headers:

    void Response_Completed(IAsyncResult result)
    {
        HttpWebRequest request = (HttpWebRequest)result.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
        String header = response.Headers["Set-Cookie"]; 
    

    I never managed to get the CookieContainer.GetCookies() method to work.

    0 讨论(0)
提交回复
热议问题