Search code examples
mongodbasp.net-web-apimaui

I can't connect ASP.NET Web API with .NET Maui


swagger ui

I want to connect my first maui test app with ASP.NET Web API that retrieves data from mongoDB. When the ASP.NET Web API is running, I can easily retrieve my data from Swagger UI, but when it comes to retrieving data in my MAUI app, I get an error

Connection Failure

Could you explain me why is this happening and what I should do about it?

Here is my code from MAUI app:

private async void OnSubmitClicked(object sender, EventArgs e)
{
    string pesel = peselEntry.Text;

    try
    {
        var response = await App.HttpClient.GetAsync($"https://localhost:7183/api/Patients/Test");
        if (response.IsSuccessStatusCode)
        {
            var patient = await response.Content.ReadFromJsonAsync<Patients>();
            await DisplayAlert("Oto dane", $"Imię: {patient.Name}, Nazwisko: {patient.Surname}", "OK");
        }
        else
        {
            await DisplayAlert("Błąd", "Pacjent nie znaleziony.", "OK");
        }
    }
    catch (Exception ex)
    {
        await DisplayAlert("Błąd", $"Wystąpił problem: {ex.Message}", "OK");
    }
}

I just added CORS to program.cs in ASP.NET, but it didn't help


Solution

  • A WinForms app runs on your local machine, so can access a localhost site. A Maui app runs (usually) in an emulator, which is a different machine.

    As IISExpress can only serve to localhost, you need to setup your site to run under IIS. You can still debug from there! The Maui app then needs to call that site by machine name or IP address.