Xamarin应用连接本地自签名证书Web API遇SSL认证错误,配置DangerousAcceptAnyServerCertificateValidator时提示未定义的解决方案咨询
Hey there! I totally get how frustrating this SSL error can be when you're just trying to test your app. Let's get this sorted out for you.
Why You're Seeing "DangerousAcceptAnyServerCertificateValidator is not defined"
That static property is a newer addition (available in .NET 5+ and recent Xamarin.Forms versions). If you're working with an older Xamarin project, it might not be available in your environment. No worries though—we can achieve the same result with a manual callback.
The Working Solution for Testing
Instead of relying on that predefined validator, we can directly implement the certificate validation callback to always return true (again, only for testing purposes). Here's the code you need:
// Create an HttpClientHandler and override the certificate validation var httpHandler = new HttpClientHandler(); // This callback skips all certificate checks—use only for testing! httpHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true; // Initialize your HttpClient with this handler var httpClient = new HttpClient(httpHandler); // Now use this httpClient to call your local Web API // Example: var apiResponse = await httpClient.GetAsync("https://your-local-api-address/api/your-endpoint");
Important Notes
- Never use this in production: Disabling certificate validation completely removes SSL security, leaving your app vulnerable to man-in-the-middle attacks. Once you're done testing, you'll need to set up proper certificate trust (like installing your local API's certificate on the test devices, or implementing proper certificate pinning).
- If you later move to a newer .NET/Xamarin version, the
DangerousAcceptAnyServerCertificateValidatorproperty should work—you can replace the lambda with:httpHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
That should get your Xamarin app talking to your local Web API without the SSL error for testing. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者Raluido

