0

I'm creating a mobile app with Maui Blazor for the first time (also first mobile app). Since it's my first time I followed a tutorial where they created a minimal API which worked both with Windows Application and Android emulator for me.

Then I made a new ASP.NET Core Web API project which I want to use instead. The api-calls works in swagger and I when I run a windows application but not when I run the Android emulator where it casts an exception in the service class on the line:

HttpResponseMessage response = await _httpClient.GetAsync($"{_url}/item");

UPDATE: The exception is "One or more errors occurred. (java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.)"

InnerException:

  • System.Net.WebException
  • base: System.InvalidOperationException
  • status: System.Net.WebExceptionStatus.UnknownError

Service class:

private readonly HttpClient _httpClient;
private readonly string _baseAddress;
private readonly string _url;
private readonly JsonSerializerOptions _jsonSerializerOptions;

public DataService(HttpClient httpClient)
{           
    _httpClient = httpClient;

    _baseAddress = DeviceInfo.Platform == DevicePlatform.Android ? "http://10.0.2.2:XXXX" : "https://localhost:XXXX";
    _url = $"{_baseAddress}/api";

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

public async Task<List<Item>> GetAll()
{
    List<Item> items = new List<Item>();

    if (Connectivity.Current.NetworkAccess != NetworkAccess.Internet)
    {
        Debug.WriteLine("No internet access.");
        return items;
    }

    try
    {
        // ERROR HERE
        HttpResponseMessage response = await _httpClient.GetAsync($"{_url}/item");
        
        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
        
            items = JsonSerializer.Deserialize<List<Item>>(content,                    _jsonSerializerOptions);
        }
        else
        {
            Debug.WriteLine("Non Http 2xx response");
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine($"Exception: {ex.Message}");
    }

    return items;
}

API program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Tried the following:

  • Making api calls with url
  • Checked network connection on the emulator
  • Added CORS to my api

Since it worked before I suspect it has to do with my API but I don't know what.

Any help would be appreciated, Thanks!

  • What specifically is the exception? Have you checked that your webserver is setup to allow remote connections? Have you checked connectivity to the server from the device (or emulator) browser? – Jason May 17 '23 at 14:35
  • Does the exception have an `InnerException` property? If so, what is that exception? Please paste, into question, the full text of both the original exception and the InnerException, if any. – ToolmakerSteve May 17 '23 at 15:04
  • I'm fairly new to this but I checked and my server is allowing remote connections. Checked the exception before and it said unkown. But I got this now: (java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.). Googled again and seems like i need to add cert in my network_security_config file? How do I add the required cert and where do I get the cert from? – Skogskotten May 17 '23 at 15:08
  • `CertPathValidatorException` is a pretty common and well documented issue – Jason May 17 '23 at 16:15
  • You can check this [answer](https://stackoverflow.com/a/71196389/19335715) about the `CertPathValidatorException` . The answer mentioned that HttpClientHandler actually uses AndroidMessageHandler as its underlying handler and he give the solution to fix this error. – Guangyu Bai - MSFT May 18 '23 at 08:09

0 Answers0