Search code examples
c#androidpostxamarinwebrequest

Xamarin Android httpwebrequest, Cannot access a disposed object


I have an android mobile app , and i want to send webrequest to server to post some data, but before posting the data i send an http get request to get some data, and then sending post request , first i receive get successfully but when i send the post request it throws bellow exception on this line of my code requestStream.Write(bytes, 0, bytes.Length);

the exception is :

System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Sockets.NetworkStream'.

and here is my get and post request code GET:

public void GetTokenInfo()
        {

            try
            {
                var uri = new Uri(string.Format(_host + "webserver/SesTokInfo", string.Empty));
                var webRequest = WebRequest.Create(uri);
                using (var response = webRequest.GetResponse() as HttpWebResponse)
                {
                    using (var requestStream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(requestStream))
                        {
                            var content = reader.ReadToEnd();
                            XmlDocument xDocument = new XmlDocument();
                            xDocument.LoadXml(content);
                            XmlElement root = xDocument.DocumentElement;
                            if (IsResponseReturned(root))
                            {
                                GlobalConfig.SessionId = root.GetElementsByTagName("SesInfo")[0].InnerText;
                                GlobalConfig.Token = root.GetElementsByTagName("TokInfo")[0].InnerText;

                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
            }
        }

with this code i get receive my result without any problem, and here is my POST:

 public WebResponse PostData(string body, string url)
        {
            WebResponse webResponse = null;
            try
            {
                var uri = new Uri(string.Format(_host + url, string.Empty));
                var webRequest = (HttpWebRequest)WebRequest.Create(uri);
                webRequest.Headers.Add("Cookie",
                    GlobalConfig.SessionId);
                webRequest.Headers.Add("_RequestVerificationToken", GlobalConfig.Token);
                webRequest.Method = "POST";
                webRequest.ContentType = "application/xml";
                byte[] bytes = Encoding.UTF8.GetBytes(body);
                webRequest.ContentLength = bytes.Length;
                Stream requestStream = webRequest.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                webResponse = webRequest.GetResponse();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            return webResponse;
        }

i have searched and tried ways but i did not get the solution , and plus when i comment the first function, and only run the second function it will work fine but when i run the first and then the second it throws the exception , does anything belong to dispose the stream and web response from first code? i think using statement is already disposes them.

any help appreciated.


Solution

  • After trying many ways and read above answers and try them finally i get solved the problem by making the both code like the following , GET one:

                    var uri = new Uri(string.Format(_host + "webserver/SesTokInfo", string.Empty));
                    var webRequest = WebRequest.Create(uri);
                    using (var response = webRequest.GetResponse() as HttpWebResponse)
                    {
                        using (var reader = new StreamReader(response.GetResponseStream()))
                        {
                            var content = reader.ReadToEnd();
                            XmlDocument xDocument = new XmlDocument();
                            xDocument.LoadXml(content);
                            XmlElement root = xDocument.DocumentElement;
                            if (IsResponseReturned(root))
                            {
                                GlobalConfig.SessionId = root.GetElementsByTagName("SesInfo")[0].InnerText;
                                GlobalConfig.Token = root.GetElementsByTagName("TokInfo")[0].InnerText;
    
                            }
                        }
                    }
    

    and POST one:

                    var uri = new Uri(string.Format(_host + url, string.Empty));
                    var webRequest2 = (HttpWebRequest)WebRequest.Create(uri);
    
    
                    webRequest2.Headers.Add("Cookie",
                        GlobalConfig.SessionId);
                    webRequest2.Headers.Add("_RequestVerificationToken", GlobalConfig.Token);
                    webRequest2.Method = "POST";
                    webRequest2.ContentType = "application/xml";
    
                    byte[] bytes = Encoding.UTF8.GetBytes(body);
                    webRequest2.ContentLength = bytes.Length;
                    StreamWriter writer = new StreamWriter(webRequest2.GetRequestStream());
                    writer.Write(bytes);
                    webResponse = webRequest2.GetResponse();
    

    when i use the request stream inside using block it will still throw the exception but with out using block it will work :)