1

I have this code which is working absolutely fine on Windows Phone 8.1.

Unfortunately it doesn't work on Windows 8.1. The response that i am getting from this request give me a page with session expired, the same way it would be without the cookie. The code seems to be fine but it looks like the cookie doesn't get set or I am missing something else...

Is there something that needs to be added to make it work for Windows Store apps?

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

   using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Add("Cookie", value.ToString());
                htmlPage = await client.GetStringAsync("https://www.someurl.com" + querystring);
            }
SunnySonic
  • 1,318
  • 11
  • 37

2 Answers2

1

Your code works fine to pass in headers, but not cookies. Try this code instead:

        HttpClientHandler handler = new HttpClientHandler();
        handler.CookieContainer.Add(new Uri("http://www.microsoft.com"), new Cookie("MyCookieName", "MyCookieValue"));
        using (var client = new HttpClient(handler))
        {
            htmlPage = await client.GetStringAsync("https://www.microsoft.com");
        }
Matt Small
  • 2,182
  • 1
  • 10
  • 16
  • Thanks for your answer, but it also doesn't work. What is baffling me is though that the code works fine on Windows Phone, but not on Windows and I am trying to find out the differences. Thought about user agents, but tried different ones as well. Always working fine on WP but not on Windows. Not sure what could be the problem. – SunnySonic Oct 05 '14 at 11:42
  • This code works well for me on Windows 8.1. From Fiddler using this exact code on Windows 8.1: GET https://www.microsoft.com/ HTTP/1.1 Host: www.microsoft.com Cookie: MyCookieName=MyCookieValue Connection: Keep-Alive – Matt Small Oct 09 '14 at 14:38
  • Maybe it has specifically to do with the server that i am trying to use. I rewrote my code using the windows.web.http client which is recommended to be used anyways by microsoft. Thanks for your help though!! – SunnySonic Oct 10 '14 at 18:18
0

System.Net.Http seems to work differently on W8.1 than on WP8.1. I could never figure out the difference.

Nevertheless I rewrote my code using Windows.Web.Http, which is new on 8.1 and recommended to use. Here an example how to attach cookies with the new httpclient:

var bpf = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
var cm = bpf.CookieManager;
var cookie = new HttpCookie("name", ".example.com", "/") { Value = "value" };
cm.SetCookie(cookie);
var http = new HttpClient(bpf);
await http.PostAsync(new Uri("http://example.com/"), new HttpStringContent("content"));

As well as here a sample:

http://code.msdn.microsoft.com/windowsapps/HttpClient-sample-55700664

SunnySonic
  • 1,318
  • 11
  • 37