Reputation: 21
I'm developing a .NET MAUI application to run on both windows and android devices. Up til now I've purely been using the Windows Machine and Android Emulator Launch options. However Android Emulator is really slow so I decided to attempt to use a physical android phone instead. I've setup the android phone in developer mode and connected to my laptop via usb cable. I have managed to get my MAUI app launching onto my android phone using the "Android Local Device" option.
My issue lies when I attempt to send a HTTP message to my ASP.NET Core Web API project. I have a line of code that detects which platform the device is and if it is android then it uses 10.0.2.2 instead of localhost for the URL:
public static string BaseUrl = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5137/api" : "http://localhost:5137/api";
I have also attempted to use "http://192.168.0.22:5137/api" instead.
I have a network_security_config.xml file in my Resources\XML folder which works perfectly for the Windows Machine and Android Emulator.
Essentially, when I attempt to send the http message such as below:
HttpResponseMessage responseMessage = await httpClient.PostAsync("", content);
it doesn't seem to send anything or fails to send anything. Nothing is ever recieved in the API. The following pop up occurs on screen of the android phone "the request was cancelled due to the configured HttpClient. timeout of 100 seconds elapsing"
as I've already said, my code works completely fine through Windows Machine and Android Emulators.
I'm thinking the error must be something to do with the fact the app is running on a different device. Local MAUI code such as changing pages and button clicks work fine but anything APi related is a no go. I'm not an expert when it comes to MAUI development, this is only my first ever real project so baby instructions are much appreciated.
Any assistance at all is welcome.
Upvotes: 1
Views: 1597
Reputation: 441
You should use dev tunnels for your backend server. The web API needs exposure to your simulators. To make the backend visible to your apps, run this in your terminal devtunnel host -p {portNumber} --allow-anonymous --protocol https
Read more here.
Upvotes: 0
Reputation: 21
The Issue persisted in the fact that my Web API wasn't set up to allow remote connections. Here's how I altered both my MAUI app and ASP.NET Core Web API to work on an Android Local Device via USB-C cable:
For reasons I'm not qualified enough to know the answer to yet, it won't work when using "http://10.0.2.2:5137" even though this works using the Android emulator. But by hardcoding the current IP it works great.
Thanks for the help Jason!
Upvotes: 0