I am trying to fetch a localhost api in a mobile application built using .NET MAUI
MainPage.xaml.cs
namespace LocalApp
{
public partial class MainPage : ContentPage
{
int count = 0;
public MainPage()
{
InitializeComponent();
}
private async void Btn_Clicked(object sender, EventArgs e)
{
await DisplayAlert("Button Clicked", "response", "Ok");
var httpClient = new HttpClient();
var url = DeviceInfo.Platform == DevicePlatform.Android
? "http://10.0.2.2:5214/weatherforecast"
: "http://localhost:5214/weatherforecast";
var response = await httpClient.GetAsync(url);
try
{
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
api.Text = content;
}
else
{
await DisplayAlert("Error", "Wrong status code", "ok");
}
}
catch (Exception ex) {
await DisplayAlert("Exception", $"{ex.Message}", "Ok");
}
}
}
}
LocalApp/Platforms/MainApplication.cs
using Android.App;
using Android.Runtime;
namespace LocalApp
{
[Application(UsesCleartextTraffic = true)]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
}
for debugging purposes I have set UsesCleartextTraffic to true!
Also the application works well on Windows platform but run out of a runtime exception on android.
Help appreciated