dotnet / android

.NET for Android provides open-source bindings of the Android SDK for use with .NET managed languages such as C#
MIT License
1.92k stars 526 forks source link

Wifi disconnect breaks HttpMessageHandler #6392

Closed SSpormann closed 4 months ago

SSpormann commented 2 years ago

Steps to Reproduce

  1. Connect to a WIFI without InternetAccess from within the App using this Code:

public int ConnectToWifi29andUp(String ssid, String password)
        {
            try
            {
                bool connectionSuccess = false;
                bool connectionResultAvailable = false;

                networkCallback.NetworkAvailable += delegate (Network network)
                {
                    connectionSuccess = true;
                    connectionResultAvailable = true;
                    ;
                };

                networkCallback.NetworkUnAvailable += delegate (bool result)
                {
                    connectionSuccess = false;
                    connectionResultAvailable = true;
                    ;
                };

                ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;

                var wifiManager = Android.App.Application.Context.GetSystemService(Context.WifiService) as WifiManager;
                if (!wifiManager.IsWifiEnabled)
                {
                    wifiManager.SetWifiEnabled(true);
                }
                //NetworkStatus result = wifiManager.RemoveNetworkSuggestions(suggestionsList);

                //result = wifiManager.AddNetworkSuggestions(suggestionsList);

                WifiNetworkSpecifier specifier = new WifiNetworkSpecifier.Builder()
                    .SetSsid(ssid)
                    .SetWpa2Passphrase(password)
                    .Build();

                NetworkRequest request = new NetworkRequest.Builder()
                    .AddTransportType(TransportType.Wifi)
                    .RemoveCapability(NetCapability.Internet)
                    .SetNetworkSpecifier(specifier)
                    .Build();

                connectivityManager.RequestNetwork(request, networkCallback);

                int connectionTimeout = 30000;

                while (!connectionResultAvailable && (connectionTimeout -= 1000) >= 0)
                {
                    Task.Delay(1000).Wait();
                }
                return connectionSuccess ? 1 : 0;
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.ToString());
            }
            return 0;
        }

        private static Android.App.Result GetResultFromCode(int code) =>
        code switch
        {
            0 => Android.App.Result.Ok, // newly added
            2 => Android.App.Result.Ok, // wifi already there
            _ => Android.App.Result.Canceled
        };
  1. Disconnect the Wifi like this:
    public void DisconnectWifi(string ssid)   public void DisconnectWifi(string ssid)
        {
            if (Android.OS.Build.VERSION.SdkInt > BuildVersionCodes.P)
            {
                ConnectivityManager connectivityManager = Android.App.Application.Context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
                connectivityManager.UnregisterNetworkCallback(networkCallback);
            }
            else
            {
                var wifiManager = Android.App.Application.Context.GetSystemService(Context.WifiService) as WifiManager;
                wifiManager.SetWifiEnabled(false);
                wifiManager.SetWifiEnabled(true);
            }
        }
  2. Try to use a HttpMessageHandler to connect to any URL it does not Work the Exception thrown is

Network is unreachable

Expected Behavior

I would imagine after the Restoration of a connection to a Wifi with an internetconnection that the Exception goes away.

Actual Behavior

But the behavior stais till you reboot the app, reusing the handler and reinitializing the handlerfactory seems unefective. But in this case I recieve a different exception.

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'SocketsHttpHandler'.
  at System.Net.Http.SocketsHttpHandler.CheckDisposed () [0x00008] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs:22 
  at System.Net.Http.SocketsHttpHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/SocketsHttpHandler.cs:336 
  at System.Net.Http.SocketsHttpHandler.System.Net.Http.IMonoHttpClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System.Net.Http/corefx/SocketsHttpHandler.Mono.cs:48 
  at System.Net.Http.HttpClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mcs/class/System.Net.Http/HttpClientHandler.cs:198 
  at System.Net.Http.DelegatingHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00019] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/DelegatingHandler.cs:54 
  at Microsoft.AspNetCore.Http.Connections.Client.Internal.AccessTokenHttpMessageHandler.<>n__0 (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00000] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.Internal.AccessTokenHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x0009f] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.Internal.LoggingHttpMessageHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00095] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered (System.Threading.Tasks.Task`1[TResult] sendTask, System.Net.Http.HttpRequestMessage request, System.Threading.CancellationTokenSource cts, System.Boolean disposeCts) [0x000b3] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.Net.Http/src/System/Net/Http/HttpClient.cs:531 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.NegotiateAsync (System.Uri url, System.Net.Http.HttpClient httpClient, Microsoft.Extensions.Logging.ILogger logger, System.Threading.CancellationToken cancellationToken) [0x00257] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.GetNegotiationResponseAsync (System.Uri uri, System.Threading.CancellationToken cancellationToken) [0x00080] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.SelectAndStartTransport (Microsoft.AspNetCore.Connections.TransferFormat transferFormat, System.Threading.CancellationToken cancellationToken) [0x00180] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsyncCore (Microsoft.AspNetCore.Connections.TransferFormat transferFormat, System.Threading.CancellationToken cancellationToken) [0x00127] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.StartAsync (Microsoft.AspNetCore.Connections.TransferFormat transferFormat, System.Threading.CancellationToken cancellationToken) [0x00091] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync (System.Net.EndPoint endPoint, System.Threading.CancellationToken cancellationToken) [0x00114] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionFactory.ConnectAsync (System.Net.EndPoint endPoint, System.Threading.CancellationToken cancellationToken) [0x001bf] in <246d837b124a4624a33ae937a4e5ac18>:0 
  at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/Common/src/CoreLib/System/Threading/Tasks/ValueTask.cs:813 
  at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore (System.Threading.CancellationToken cancellationToken) [0x000a5] in <8dd6fa3545a347338587f9958af16302>:0 
  at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncInner (System.Threading.CancellationToken cancellationToken) [0x001a4] in <8dd6fa3545a347338587f9958af16302>:0 
  at System.Threading.Tasks.ForceAsyncAwaiter.GetResult () [0x0000c] in <8dd6fa3545a347338587f9958af16302>:0 
  at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsync (System.Threading.CancellationToken cancellationToken) [0x00091] in <8dd6fa3545a347338587f9958af16302>:0

Version Information

Testest on: Android Pixel 3a with Android 11: Xamarin version: 5.0.0.2125 and Xamarin Version 5.0.0.2083

Microsoft Visual Studio Enterprise 2019 (2) Version 16.11.4 VisualStudio.16.Release/16.11.4+31727.386 Microsoft .NET Framework Version 4.8.04084 Installierte Version: Enterprise .NET Core Debugging with WSL 1.0 .NET Core Debugging with WSL Allgemeine Azure-Tools 1.10 Bietet allgemeine Dienste für die Verwendung durch Azure Mobile Services und Microsoft Azure-Tools. ASP.NET and Web Tools 2019 16.11.75.64347 ASP.NET and Web Tools 2019 ASP.NET Web Frameworks and Tools 2019 16.11.75.64347 Weitere Informationen finden Sie unter https://www.asp.net/. Azure App Service-Tools v3.0.0 16.11.75.64347 Azure App Service-Tools v3.0.0 Azure Functions and Web Jobs Tools 16.11.75.64347 Azure Functions and Web Jobs Tools C#-Tools 3.11.0-4.21403.6+ae1fff344d46976624e68ae17164e0607ab68b10 C#-Komponenten, die in der IDE verwendet werden. Abhängig von Ihrem Projekttyp und den zugehörigen Einstellungen kann eine andere Version des Compilers verwendet werden. Erweiterung zum Debuggen von Momentaufnahmen 1.0 Detaillierte Informationen zur Visual Studio-Erweiterung zum Debuggen von Momentaufnahmen Erweiterungen der Visual Studio-Containertools 1.0 Hiermit werden Container in Visual Studio angezeigt, verwaltet und diagnostiziert. Extensibility Message Bus 1.2.6 (master@34d6af2) Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration. IncrediBuild Build Acceleration 1.5.0.13 IncrediBuild effectively reduces compilation and development times by up to 90%. IntelliCode-Erweiterung 1.0 Detaillierte Informationen zur IntelliCode Visual Studio-Erweiterung Microsoft Azure-Tools für Visual Studio 2.9 Support für Azure Cloud Services-Projekte Microsoft Continuous Delivery Tools für Visual Studio 0.4 Die Konfiguration von Azure DevOps-Pipelines von der Visual Studio-IDE aus wird vereinfacht. Microsoft JVM Debugger 1.0 Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines Microsoft MI-Based Debugger 1.0 Provides support for connecting Visual Studio to MI compatible debuggers Microsoft Visual Studio-Tools für Container 1.2 Jetzt können Sie Ihre ASP.NET Core-Anwendung in der Zielumgebung entwickeln, ausführen und überprüfen. Drücken Sie F5, um die Anwendung direkt in einem Container mit Debugfunktionen auszuführen, oder STRG+F5 zum Bearbeiten und Aktualisieren Ihrer Anwendung, ohne den Container erneut erstellen zu müssen. Mono Debugging for Visual Studio 16.10.15 (552afdf) Support for debugging Mono processes with Visual Studio. NuGet-Paket-Manager 5.11.0 NuGet-Paket-Manager in Visual Studio. Weitere Informationen zu NuGet finden Sie unter https://docs.nuget.org/. ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info Razor (ASP.NET Core) 16.1.0.2122504+13c05c96ea6bdbe550bd88b0bf6cdddf8cde1725 Provides languages services for ASP.NET Core Razor. SQL Server Data Tools 16.0.62107.28140 Microsoft SQL Server Data Tools TypeScript-Tools 16.0.30526.2002 TypeScript-Tools für Microsoft Visual Studio Visual Basic-Tools 3.11.0-4.21403.6+ae1fff344d46976624e68ae17164e0607ab68b10 Visual Basic-Komponenten, die in der IDE verwendet werden. Abhängig von Ihrem Projekttyp und den zugehörigen Einstellungen kann eine andere Version des Compilers verwendet werden. Visual F# Tools 16.11.0-beta.21322.6+488cc578cafcd261d90d748d8aaa7b8b091232dc Microsoft Visual F# Tools Visual Studio-Tools für Container 1.0 Visual Studio-Tools für Container Visual Studio Code-Debugadapter-Hostpaket 1.0 Interopebene zum Hosten der Visual Studio Code-Adapter in Visual Studio VisualStudio.DeviceLog 1.0 Informationen zum Paket VisualStudio.Foo 1.0 Information about my package VisualStudio.Mac 1.0 Mac Extension for Visual Studio Xamarin 16.11.000.190 (d16-11@2391ed9) Visual Studio-Erweiterung, um Entwicklung für Xamarin.iOS und Xamarin.Android zu ermöglichen. Xamarin Designer 16.11.0.17 (remotes/origin/11e0001f0b17269345e80b58fb3adf1ba4efe2cd@11e0001f0) Visual Studio-Erweiterung zum Aktivieren der Xamarin Designer-Tools in Visual Studio. Xamarin Templates 16.10.5 (355b57a) Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms. Xamarin.Android SDK 11.4.0.5 (d16-11/7776c9f) Xamarin.Android Reference Assemblies and MSBuild support. Mono: c633fe9 Java.Interop: xamarin/java.interop/d16-11@48766c0 ProGuard: Guardsquare/proguard/v7.0.1@912d149 SQLite: xamarin/sqlite/3.35.4@85460d3 Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-11@683f375 Xamarin.iOS and Xamarin.Mac SDK 15.0.0.8 (0796d78dc) Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.
SSpormann commented 2 years ago

I have build a Sample-Project to show the error, you can download it here:

https://support.reiner-sct.de/test/WifiConnectBreaksTheInternet.zip

Playing with the used http implementation in build properties extended the error message differs, but the result stays the same.

jpobst commented 4 months ago

With support for Classic Xamarin.Android ended May 1st, 2024, this issue is likely no longer relevant.

If this still persists in .NET 8+, please open a new issue with updated information based on net8.0-android or greater. Please include a link to this issue for context.