Maui中的Android使用https时信任所有证书
前言
最近使用Maui+blazor写了一个Android app,需要调用webapi接口,同时需要用websock与服务器通信,在使用http和https中遇到一些问题
http
Android默认禁止http,想要使用http需要在Platforms\Android目录下找到AndroidManifest.xml文件,然后在application节点中添加android:UsesCleartextTraffic="true" 如图
或者在MainApplication类中的Application特性中添加UsesCleartextTraffic = true
[Application(UsesCleartextTraffic =true)]public class MainApplication : MauiApplication{public MainApplication(IntPtr handle, JniHandleOwnership ownership): base(handle, ownership){}protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();}
https
使用https时因为需要证书,目前没有证书,就在iis中创建了个自签名证书(webapi发布到了iis),这时想要调用api接口需要信任证书,官网上给的解决方案如下
public class HttpsClientHandlerService{public HttpMessageHandler GetPlatformMessageHandler(){
#if ANDROIDvar handler = new Xamarin.Android.Net.AndroidMessageHandler{ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>{if (cert != null && cert.Issuer.Equals("CN=LAPTOP-CL5H1EIT"))return true;return errors == System.Net.Security.SslPolicyErrors.None;}};return handler;
#elif IOSvar handler = new NSUrlSessionHandler{TrustOverrideForUrl = IsHttpsLocalhost};return handler;
#elsethrow new PlatformNotSupportedException("Only Android and iOS supported.");
#endif}#if IOSpublic bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust){return url.StartsWith("https://localhost");}
#endif}
builder.Services.AddScoped(sp => new HttpClient(new HttpsClientHandlerService().GetPlatformMessageHandler()) { BaseAddress = new Uri("https://192.168.6.13") });
先在一个类中创建一个反回httpmessagehandle
的方法,在实例化httpclient时传入,这时在请求接口时cert参数会获取证书的信息,这里做了一下判断,也可以直接返回true
websocket
在websocket使用wss请求连接如下
ClientWebSocket webSocket = new ClientWebSocket();webSocket.Options.RemoteCertificateValidationCallback = (message,cain,cailn,error) => true;await webSocket.ConnectAsync(new Uri("wss://192.168.6.13/pumpsys/Websocket/GetWebsocketConnection"), disposalTokenSource.Token);await SendMessageAsync();await ReceiveLoop();
和使用httpclient调用接口差不多,在option中有个remotecertificatevalidationcallback的委托,
他在请求连接时也会返回证书信息在cain参数中