Repository navigation
Closed
Description
The ASP.NET Core Web API app is up and running. Making requests to the API endpoints from Blazor Web Assembly works perfectly fine. Whenever making request from the .NET MAUI Blazor App it's throwing the following exception:
[DOTNET] System.Net.Http.HttpRequestException: Connection refused (localhost:44363)
[DOTNET] ---> System.Net.Sockets.SocketException (111): Connection refused
[DOTNET] at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken
[DOTNET] cancellationToken) in System.Net.Sockets.dll:token 0x60002b9+0x1f
[DOTNET] at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) in System.Net.Sockets.dll:token 0x60002b3+0x26
[DOTNET] at Syst
[DOTNET] em.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken) in System.Net.Sockets.dll:token 0x600029c+0xa4
[DOTNET] at System.Net.Http.HttpConnectionP
[DOTNET] ool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x6000700+0x1b4
[DOTNET] --- End of inner exception stack trace ---
[DOTNET] at System.Net.Http.HttpC
[DOTNET] onnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x6000700+0x298
[DOTNET] at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpReque
[DOTNET] stMessage request, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006ff+0x14d
[DOTNET] at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellati
[DOTNET] onToken) in System.Net.Http.dll:token 0x6000701+0x8f
[DOTNET] at System.Net.Http.HttpConnectionPool.SendUsingHttp11Async(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f1
[DOTNET] +0x15d
[DOTNET] at System.Net.Http.HttpConnectionPool.DetermineVersionAndSendAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f2+0x224
[DOTNET] at System.Net.Http.HttpConne
[DOTNET] ctionPool.SendAndProcessAltSvcAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f3+0x8e
[DOTNET] ssage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f4+0x99
[DOTNET] at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequ07-16 12:39:49.024 I/DOTNET (16085): at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationT
[DOTNET] oken) in System.Net.Http.dll:token 0x6000787+0x94
[DOTNET] at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in Microsoft.Extensions.Http.dll:token 0x60000c3+0xd7
[DOTNET] at MauiB
[DOTNET] lazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Common\AuthorizationDelegatingHandler.cs:line 43
[DOTNET] at Microsoft.E
[DOTNET] xtensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in Microsoft.Extensions.Http.dll:token 0x60000c8+0xef
[DOTNET] ge request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken) in System.Net.Http.dll:token 0x600022f+0x1b7
[DOTNET] lazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Common\Authoriz07-16 12:39:49.025 I/DOTNET (16085): at MauiBlazor.Share
[DOTNET] d.Services.UserService.LoginAsync(LoginModel loginModel) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Services\UserService.cs:line 132
[DOTNET] at MauiBlazorApp.Components.IdentityComponents.LoginComponent.HandleValidSubmitAsync() in D:\GitHub
[DOTNET] \CleanArchitecture\src\ClientApps\MauiBlazorApp\MauiBlazorApp\Components\IdentityComponents\LoginComponent.razor.cs:line 51There is no CORS issue because the API app is allowing any origin as follows:
services.AddCors(options =>
{
options.AddPolicy(myAllowSpecificOrigins, builder =>
{
builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed(_ => true);
});
});Please help me how can I overcome the issue so that I can make requests to the ASP.NET Core REST endpoints from .NET MAUI Blazor app successfully. Thanks in advance.
Reacted by Eilon Lipton, Laftek, Alexander Blyth, Aliaksei Osipau and NATTO
Activity
Eilon commentedon Jul 19, 2021
Hi @tanvirarjel can you share more info about this setup? Is it all on Windows, with .NET MAUI targeting WinUI, and the ASP.NET Core server is running locally on the same Windows machine?
tanvirarjel commentedon Jul 19, 2021
@Eilon Here is the complete repo: https://github.com/TanvirArjel/CleanArchitecture
Yes! It's on Windows. Both servers are running on Windows local machine.
Eilon commentedon Jul 19, 2021
BTW CORS shouldn't matter here because CORS applies only to browsers making calls to a remote server. In this case it's a .NET Core app making a call, so CORS isn't a factor one way or another.
Eilon commentedon Jul 19, 2021
The first thing that I can think of is some issue related to HTTP vs. HTTPS. Is everything consistently using HTTPS in this scenario?
tanvirarjel commentedon Jul 19, 2021
@Eilon
I think so. It would be great if you run the repository on your machine and test.
Eilon commentedon Jul 19, 2021
@tanvirarjel in that case it will likely take a while for me to get to this because it could involve a lot of investigation. Ideally we have minimal repro projects for this so there are fewer possible problems.
tanvirarjel commentedon Jul 21, 2021
@Eilon Okay! I shall provide a minimal repo soon.
tanvirarjel commentedon Aug 5, 2021
@Eilon Here is the minimal repo to reproduce the issue: https://github.com/TanvirArjel/MauiDemo. After running both API and MAUI Blazor app in debug mode, please click on the FetchData menu and see the debug output.
This has been an irritating issue as this blocked my MAUI learning. Please let me know the update.
Thanks in advance.
tanvirarjel commentedon Aug 19, 2021
@Eilon Could you please give me an update on this issue?
Thank you.
Eilon commentedon Aug 19, 2021
Hi @tanvirarjel I updated your project to be compatible with preview7/RC1 and it seems to work just fine for me. First I started the ASP.NET Core server so that the API would run on port 44393 (using HTTPS), then I deployed the WinUI project and ran it from the Start Menu (there's a bug right now in VS where you can't run the WinUI app directly), and it was able to do the HttpClient call to get the weather forecast.
You can see the changes I made to the app here: tanvirarjel/MauiDemo#1
(I only changed things that changed in MAUI/Blazor/WinUI, I didn't change any app code.)
tanvirarjel commentedon Aug 19, 2021
@Eilon Great to hear that. I shall test the same project and get back to you.
Thank you again.
Eilon commentedon Aug 19, 2021
Do you know if you have the ASP.NET Core HTTPS developer certificate installed?
Check out this post from Scott Hanselman: https://www.hanselman.com/blog/developing-locally-with-aspnet-core-under-https-ssl-and-selfsigned-certs
You might need to run this command line tool:
dotnet dev-certs https --trusttanvirarjel commentedon Aug 20, 2021
@Eilon I see, you have only tested with MAUI Blazor Windows UI and you did not check with MAUI Blazor Android app. For windows UI its working fine but for the MAUI Blazor Android it's not working and throwing the same error:
tanvirarjel commentedon Aug 20, 2021
@Eilon Please keep me updated after testing on your machine. This is a very crucial issue which blocked my MAUI development.
Eilon commentedon Aug 20, 2021
Oh, I see. There's probably something that needs to be done in Android to make the cert trusted. The cert trust is done on the client, so when you run the command line tool, that makes Windows trust it. But Android is using a different cert store.
34 remaining items
[Mono.Android] custom validation callback for server certificates in …
simonrozsival commentedon Jun 6, 2022
A fix for this issue has been shipped with MAUI GA.
Eagle3386 commentedon Jun 15, 2022
@simonrozsival Just to clarify things for MAUI (Blazor) consumers like me:
Doing
inside my
MauiProgram.csis supposed to result in a NRE due to the native Android handler getting called (stack trace excerpt):as is pointed out over at Bypass the certificate security check where it states:
, right?
If so, why do the aforementioned docs then state I should do
new HttpClientHandler();in that platform-specific class, i. e.Platforms\Android\MainApplication.cs, when in reality I explicit must instantiatenew AndroidMessageHandler();in that very class? Because I tried & only prevented the NRE with the latter handler…Moreover, since you stated in #68898 that
I'm totally confused how to set/overwrite the callback for debug purposes according to "current best practices".
Up to your comment, I was using this SO answer's solution to circumvent the Android Emulator failing the certificate validation.
Therefore, any help, i. e. clarification on proper
ServerCertificateCustomValidationCallbackusage for MAUI, would be greatly appreciated! 😉simonrozsival commentedon Jun 15, 2022
@Eagle3386 hi! You shouldn't get any NRE exception. The
HttpClientHandlerclass is a proxy forAndroidMessageHandleron Android so there shouldn't really be any difference.I tried reproducing it locally in a new MAUI Blazor project and I didn't get any NRE. Can you send me a minimum reproducible example based on a new MAUI Blazor app project?
https://github.com/dotnet/runtime/issues/62966
danch15 commentedon Jun 16, 2022
@simonrozsival I use Microsoft.AspNetCore.SignalR.Client.HubConnection and the DangerousTrustProvider and DangerousAndroidMessageHandlerEmitter Class, which can be started normally on Android 11, but the same code cannot be started on Android 7.1.2. (Windows Machine is OK too.)
See: https://stackoverflow.com/questions/71047509/trust-anchor-for-certification-path-not-found-in-a-net-maui-project-trying-t
The ServerCertificateCustomValidationCallback seems to have no practical effect on Android System.
By the way, the httpClient.PostAsync can be started on Android 7.1.2 and 11 if I use the DangerousTrustProvider and DangerousAndroidMessageHandlerEmitter Class. But the HubConnection cannot be started in Android 71.2, I got the Exception:
My Example code see here: https://github.com/danch15/MauiAndDevDemo/blob/main/MauiHubConnDemo.rar
================================================================================
It seems like the problem is "options.Cookies.Add(authCookie);", I add a webserver with signalR, then connect to it without cookie, it OK.
Eagle3386 commentedon Jun 16, 2022
@simonrozsival Alright, that's how I thought it ought to work. Thanks for the clarification! 👍🏻
Of course, but I'm having a really hard time producing such a POC: instead of the NRE, I'm constantly getting
Java.Security.Cert.CertificateException: 'The remote certificate was rejected by the provided RemoteCertificateValidationCallback.'with the POC's code running inside the Android Emulator.Though, researching that exception leads to numerous sources all telling me it's Xamarin's fault due to including the root cert while it's specified that it should be excluded, etc.
Can you help me yet again?
Eilon commentedon Jun 16, 2022
Hi everyone, I created a little helper class that I started using that works on Android and Windows to connect to "local" SSL: https://gist.github.com/Eilon/49e3c5216abfa3eba81e453d45cba2d4
And here's how you can use it to call from an Android emulator to a Windows-hosted ASP.NET Core app:
And to use SignalR client in .NET MAUI, here's how I use the helper:
It seems that to make it work on Android, there are two places in the handler that need to make the SSL checks go through:
ServerCertificateCustomValidationCallbackthat bypasses cert checks for localhostIHostnameVerifierthat reports that the10.0.2.2host is valid (that's how Android talks to the Windows host)Eagle3386 commentedon Jun 16, 2022
@Eilon while that's an awesome helper for local debugging purposes, my scenario differs in that my service, i. e.
HttpClient's target, isa) already hosted on a publicly available server (think of
sub.example.net)b) has a valid wildcard certificate (i. e.
*.example.net, for which my company even paid instead of using a Let's Encrypt one & that has the intermediate CA "Sectigo RSA Domain Validation Secure Server CA" & the root CA "USERTrust RSA Certification Authority")c) my set
ServerCertificateCustomValidationCallbackenters witherrorsalready being set toRemoteCertificateChainErrorsAnd according to
https://github.com/xamarin/xamarin-android/blob/3d5231ca3a094b85302b5dbd3cc074be37efa2c0/src/Mono.Android/Xamarin.Android.Net/X509TrustManagerWithValidationCallback.cs#L56-L60
(Inline code preview seems to be prevented for cross-linked repos…)
that error is only set if the internal
TrustManagerthrew an exception - which I neither see at VS's debug outputs nor within the Android Emulator, hence I simply don't know what actually failed within the remote certificate chain. 😢Eilon commentedon Jun 16, 2022
@Eagle3386 ah alright that might very well be different. My helper is only for locally hosted sites (e.g. ASP.NET Core running on your Windows machine).
Eilon commentedon Jun 16, 2022
I started a discussion topic on how to connect from Android emulators to a local ASP.NET Web API running on Windows: dotnet/maui#8131
Please check that out and let us know if you have any feedback on any of the solutions presented.
Eagle3386 commentedon Jun 17, 2022
@Eilon & @simonrozsival I still implemented Eilon's snippet nonetheless, but its
CustomHostnameVerifierisn't even reached: theCustomAndroidMessageHandler's assignedServerCertificateCustomValidationCallbackvalue is accessed first & since I'm in scenario 4 mentioned over at dotnet/maui#8131 (remote test server & real SSL certificate) the shouldn't ever happen, right?Also, I did notice these debug output lines in VS (
Callback.NREis my current attempt for Simon's initial POC request):Is my
RemoteCertificateChainErrorscaused due to missing OpenSSL?Though, I'm running the Android Emulator's default image for Android 11...
Furthermore,

ChainStatusis empty, so I'm still unable to determine the real cause:Lastly, please let me know if I should post this over at the mentioned discussion instead of this issue. I'd almost do anything just to get this chain error resolved… 😅
Eagle3386 commentedon Jun 21, 2022
Just for the sake of completeness: using @Eilon's helper helped (pun intended! 😎) solve the NRE issue & also enabled me to discover that ASP.NET Core's dev cert was included in the chain - although "invisible" as anyone can see in my screenshot above (showing 3 instead of 4 certs).
Everything else was/is discussed over at dotnet/maui/discussions/8131.