Question

I use System.Net.Http.HttpClient Object to login to a forum successfully and do many operations. Then the object may have some state, so I want to reuse the object when the program is been opened again, implementing the automatic login. I use Json.net to serialize the HttpClient Object to the IsolatedStorage, but not available. Can somebody help me? Thank you!!

//The code for initializing the HttpClient Object
HttpClientHandler handler = new HttpClientHandler();
handler.UseCookies = true;
HttpCliclient = new HttpClient(handler);

I first serialize the object using Json.net, get the json string: {"DefaultRequestHeaders":],"BaseAddress":null,"Timeout":"00:01:40","MaxResponseContentBufferSize":2147483647}

Then deserialize the json string to get the object, but the object need logining again to do operations.

        using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
            string jsonData = JsonConvert.SerializeObject(httpclient);
            System.Diagnostics.Debug.WriteLine(jsonData);
            using (IsolatedStorageFileStream stream = storeFolder.CreateFile(path))
            using (StreamWriter writer = new StreamWriter(stream))
                writer.Write(jsonData);
        }


        using (IsolatedStorageFile storeFolder = IsolatedStorageFile.GetUserStoreForApplication()) {
            string jsonData;
            using (IsolatedStorageFileStream stream = storeFolder.OpenFile(path, FileMode.Open))
            using (StreamReader reader = new StreamReader(stream))
                jsonData = reader.ReadToEnd();

            HttpClient httpclient = JsonConvert.DeserializeObject<HttpClient>(jsonData);
            //need login again to do some operations
        }
Was it helpful?

Solution

Don't try and serialize HttpClient. The chances of it working are highly unlikely. Pretty much the only state you might be able to serialize from it are the default request headers. Create a HttpClient Factory method and just serialize out the header information that you want to preserve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top