update1: After more research I'm not sure this is possible, I created a UserVoice entry on fixing it.
I'm trying to save CookieContainer on app exit or when Tombstoning happens but I've run into some problems.
I've tried to save CookieContainer in the AppSettings but when loaded, the cookies are gone.
Researching this internally, DataContractSerializer cannot serialize cookies.
This seems to be a behavior that Windows Phone inherited from Silverlight's DataContractSerializer.
After doing more research it seemed like the work around was to grab the cookies from the container and save them another way. That worked fine until I hit another snag. I'm unable to GetCookies with a Uri of .mydomain.com. I belive it's because of this bug. I can see the cookie, .mydomain.com in the domaintable but GetCookies doesn't work on that particular cookie.
There is also a problem with getting cookies out of a container too when the domain begins with a .:
CookieContainer container = new CookieContainer();
container.Add(new Cookie("x", "1", "/", ".blah.com"));
CookieCollection cv = container.GetCookies(new Uri("http://blah.com"));
cv = container.GetCookies(new Uri("http://w.blah.com"));
I found a work around for that using reflection to iterate the domaintable and remove the '.' prefix.
private void BugFix_CookieDomain(CookieContainer cookieContainer)
{
System.Type _ContainerType = typeof(CookieContainer);
var = _ContainerType.InvokeMember("m_domainTable",
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance,
null,
cookieContainer,
new object[] { });
ArrayList keys = new ArrayList(table.Keys);
foreach (string keyObj in keys)
{
string key = (keyObj as string);
if (key[0] == '.')
{
string newKey = key.Remove(0, 1);
table[newKey] = table[keyObj];
}
}
}
Only, when InvokeMember is called a MethodAccessException is thrown in SL. This doesn't really solve my problem as one of the cookies I need to preserve is HttpOnly, which is one of the reasons for the CookieContainer.
If the server sends HTTPOnly cookies, you should create a System.Net.CookieContainer on the request to hold the cookies, although you will not see or be able to access the cookies that are stored in the container.
So, any ideas? Am I missing something simple? Is there another way to save the state of the CookieContainer or do I need to save off the users info including password and re-authentic them every time the app starts and when coming back from tombstoning?
You cannot access private members outside of your assembly in WP7, even with Reflection. It's a security measure put in place to ensure you cannot call internal system APIs.
It looks like you may be out of luck.