Reputation: 31
When calling my locally hosted API from my android emulator's .NET MAUI app, I receive an error message stating that the HTTP connection failed.
I am able to successfully send requests to my local API via google chrome on the android emulator, but when attempting to hit the same URL in the application, I receive a connection failure error.
I am using "http://10.0.2.2:5223" as the base URL for my HTTP client, and I am also using Refit to create the RestService within the .NET MAUI app.
Is it possible to create an HTTP client within a .NET MAUI ContentPage, and then use it to retrieve data from the API? My team is using C# Markup for views, so I thought it would be straightforward to create the client and call our API from the C# Markup view.
I have attached the code for the view in which I created the client and attempted an API call,
internal class MainPage : ContentPage
{
private int _selectedTabIndex { get; set; } = 1;
private IAPIClient _client { get; set; }
public MainPage()
{
_client = RestService.For<IAPIClient>("http://10.0.2.2:5223");
new Action(async () => await LoadData())();
Build();
#if DEBUG
HotReloadService.UpdateApplicationEvent += ReloadUI;
#endif
}
async Task LoadData()
{
var user = await _client.GetUser();
}
...
}
and the code for the Refit client
public interface IAPIClient
{
[Get("/User")]
Task<UserModel> GetUser();
}
Really perplexed as to why I am unable to establish a connection to the API, and feel that I am misunderstanding some fundamentals about .NET MAUI. Would I need a ViewModel to faciliate this process? And if so, why?
Would really appreciate some feedback/guidance here, thanks!
Upvotes: 3
Views: 5078
Reputation: 77
Maybe it is because you are attempting to call your async LoadData from your MainPage constrtuctor?
I had a similar issue attempting to call an async function that called an API from OnInitialize
and I was able to use the asynchronous OnInitializeAsync
to get the behavior I want. Fore more info about OnInitializeAsync
... https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-8.0#component-initialization-oninitializedasync
Upvotes: 0
Reputation: 79
May be your issue is about the security setting on Android device.
Add the parameter UsesCleartextTraffic = true on [Application]
MainApplication.cs (in the folder Platforms/Android)
namespace MauiApp1
{
[Application(UsesCleartextTraffic =true)]
public class MainApplication : MauiApplication
}
Upvotes: 7