简体   繁体   中英

why is this webclient post code not being timed out when there is no network connection?

I have this function in my xamarin.ios app that posts an object to my api. The object contains strings and 1 member as a base64 string. I can't seem to get a timeout and get an exception in less than 5 minutes when there is no connection. However it seems to be timing out when there is no base 64 in the object. Any idea to get this to work? Here is my code:

public static string postData(object @params, string url)
        {
            MyWeWbClient webClient = new MyWeWbClient();

           
            try
            {
            
                webClient.Headers["content-type"] = "application/json";
                webClient.Headers.Add("Authorization", "Bearer " + Settings.GeneralSettings3);

                var reqString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(@params, Formatting.Indented));
                byte[] resByte = webClient.UploadData(url, "post", reqString);
                var resString1 = Encoding.Default.GetString(resByte);
                webClient.Dispose();

                return resString1;
            }
            catch (WebException ex)
            {
                string responseText = "";

                var responseStream = ex.Response?.GetResponseStream();

                if (responseStream != null)
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseText = reader.ReadToEnd();

                    }
                }
                throw new Exception(responseText.ToString());
            }catch(Exception ex)
            {
                throw;
            }
        }

And my custom webclient class so I can do set timeout:

   public  class MyWeWbClient : WebClient
    {
        protected override  WebRequest GetWebRequest(Uri uri)
        {
            WebRequest w = base.GetWebRequest(uri);
            w.Timeout = (int)TimeSpan.FromSeconds(10).TotalMilliseconds;//20 * 60 * 1000;
            return w;
        }
    }

Thanks in advance. Any help is appreciated.

EDIT:

The same code is working perfectly fine on xamarin.android , and its timing out if there is no internet connection like intended.

I don't recommand using webClient, I would use an external depency like restsharp.

Alternatively, you can hardcode it using Task.Run() but since its in Xamarin I couldn't say.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM