user1424876
user1424876

Reputation: 193

iOS app crashes on iphone device when using httpclient and .net maui

Build environment: Macbook M1 vscode(1.69.0) as well as vs2022 (17.3)

Steps to reproduce:

builder.Services.AddHttpClient<EndPointAHttpClient>(client =>
        {
            var EndPointA = "https://www.montemagno.com/";
            client.BaseAddress = new Uri(EndPointA);
        });
public class EndPointAHttpClient
{
    public EndPointAHttpClient(HttpClient client)
    {
        Client = client;
    }

    public HttpClient Client { get; }
}

CRASHES WHEN OPENING THE APP

Please let me know:

1. Is there any demo code that works

2. Kindly provide advise on how I can use HttpClient in a .net Maui app

Upvotes: 2

Views: 1571

Answers (1)

Dumber_Texan2
Dumber_Texan2

Reputation: 978

Use the code found here. https://github.com/dotnet/maui-samples/tree/main/6.0/WebServices/TodoREST/TodoREST/Services

Grab the RestService, IRestService, HttpsClientHandlerService and IHttpsClientHandlerService.

Get the Contstants file as well.

https://github.com/dotnet/maui-samples/blob/main/6.0/WebServices/TodoREST/TodoREST/Constants.cs

Makes sure you add your Url to the HttpsClientHandlerService like so. I was getting a System.Net.WebException: Error: TrustFailure. The only way I was able to catch what was happening was using Sentry.io. I guessed that this might be the problem.

public bool IsSafeUrl(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
        {           
            if (url.StartsWith("https://localhost") || url.StartsWith("https://yourservice.azurewebsites.net"))
                return true;
            return false;
        }

Then change this line.

var handler = new NSUrlSessionHandler
            {
                TrustOverrideForUrl = IsSafeUrl
            };

Upvotes: 1

Related Questions