C
C#9mo ago
.Abdulrahman

✅ Android Emulator in MAUI is not connecting to webAPI

Hey there! I am trying to get data using web API but this exception raises everytime: [0:] Exception when accessing http://10.0.2.2:5191/api/SalesOffice/offices-with-property-counts: Connection failure I did the network_security_config and everything but nothing worked .. it works when I tried it on windows app, but android emulator gives the above exception
9 Replies
.Abdulrahman
.AbdulrahmanOP9mo ago
network_secuirty_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourpackage">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true">

<!-- Add your activities, services, receivers, etc. here -->

</application>

</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourpackage">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:networkSecurityConfig="@xml/network_security_config"
android:supportsRtl="true">

<!-- Add your activities, services, receivers, etc. here -->

</application>

</manifest>
The class that handles the request
c#

public RestDataService()
{
_httpClient = new HttpClient();

_baseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5191" : "https://localhost:7219";


_url = $"{_baseAddress}/api";

_jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}



//---------------- Return All Sales Offices.
public async Task<List<SalesOffices>> GetSalesOfficesAsync()
{
List<SalesOffices> salesOffices = new List<SalesOffices>();
if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
{
Debug.WriteLine("No Internet");
return salesOffices;
}

// Define the URL before making the request
string requestUrl = $"{_url}/SalesOffice/offices-with-property-counts";

try
{
HttpResponseMessage response = await _httpClient.GetAsync(requestUrl);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
salesOffices = JsonSerializer.Deserialize<List<SalesOffices>>(content, _jsonSerializerOptions);
}
else
{
Debug.WriteLine("Non Http 2xx response");
}
Debug.WriteLine($"Response from {requestUrl}: {response.Content}");
}
catch (Exception ex)
{
// Include the URL in the catch block message
Debug.WriteLine($"Exception when accessing {requestUrl}: {ex.Message}");
}


return s
}
c#

public RestDataService()
{
_httpClient = new HttpClient();

_baseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:5191" : "https://localhost:7219";


_url = $"{_baseAddress}/api";

_jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
}



//---------------- Return All Sales Offices.
public async Task<List<SalesOffices>> GetSalesOfficesAsync()
{
List<SalesOffices> salesOffices = new List<SalesOffices>();
if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
{
Debug.WriteLine("No Internet");
return salesOffices;
}

// Define the URL before making the request
string requestUrl = $"{_url}/SalesOffice/offices-with-property-counts";

try
{
HttpResponseMessage response = await _httpClient.GetAsync(requestUrl);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
salesOffices = JsonSerializer.Deserialize<List<SalesOffices>>(content, _jsonSerializerOptions);
}
else
{
Debug.WriteLine("Non Http 2xx response");
}
Debug.WriteLine($"Response from {requestUrl}: {response.Content}");
}
catch (Exception ex)
{
// Include the URL in the catch block message
Debug.WriteLine($"Exception when accessing {requestUrl}: {ex.Message}");
}


return s
}
leowest
leowest9mo ago
$mauiapi
MODiX
MODiX9mo ago
How to access WEB API using dev tunnels in MAUI? Click here to read the dev blog post! The alternatives without dev tunnels are, A and B(you dont need to do both!): A) By enabling UsesCleartextTraffic and running the API without HTTPS, type $mauiapihttp for more info. B) By overriding the native http handler to support localhost and self signed CA, type $mauiapihttps for more.
leowest
leowest9mo ago
did u also configure your api to run over http? did u also configure it to bind to your ip 10.0.... or all ips with 0.0.0.0 the simplest route is just using dev tunnels then u dont need to do any of these.
Lex Li
Lex Li9mo ago
Android emulators are not directly connected to your host machine, https://docs.lextudio.com/blog/how-to-let-android-emulator-access-iis-express-f6530a02b1d3
Half-Blood Programmer
How to Let Android Emulator Access IIS Express
This post is about how to let Android emulator access web apps hosted on IIS Express.
leowest
leowest9mo ago
with MAUI you can directly access 127.0.0.1, but there are some caveats to it so if u just use the local network ip u have a way easier time doing it if u dont want dev tunnels which is just running the api in http instead of https with the proper ip setup or just 0.0.0.0
.Abdulrahman
.AbdulrahmanOP9mo ago
Yes if you mean this one,
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:11398",
"sslPort": 44342
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "api/SalesOffice",
"applicationUrl": "http://localhost:5191/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7219;http://localhost:5191",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:11398",
"sslPort": 44342
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "api/SalesOffice",
"applicationUrl": "http://localhost:5191/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7219;http://localhost:5191",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
I'll try it, thank you so much everyone! Dev Tunnel worked, Much appreciated. 🙏🏾
leowest
leowest9mo ago
@.Abdulrahman glad it worked, and yes I meant that file, u would have to change the localhost to either ur local ip or 0.0.0.0 which means bind to all interfaces but with devtunnels u dont need to do any of that.
MODiX
MODiX9mo ago
Use the /close command to mark a forum thread as answered
Want results from more Discord servers?
Add your server