Xamarin.Forms HTTPS and Self Signed Certificate Issue

后端 未结 2 1195
情书的邮戳
情书的邮戳 2020-12-18 09:06

I am using Xamarin.Forms and my priority is UWP. I am trying to make a post request via System.Net.Http.HttpClient and my code looks like this

p         


        
相关标签:
2条回答
  • 2020-12-18 09:32

    A workaround for using self-signed certificates is to insert the following code before initialising your HttpClient in order to ignore SSL certificate errors:

    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    

    Make sure to include System.Net.

    Hope this helps.

    0 讨论(0)
  • 2020-12-18 09:32

    This code help for resolve the below error in Xamarin- Windows (UWP) - Windows 8.1

    "The text associated with this error code could not be found."

      public interface IServerCommunication
      {
       Task<string> GetFromServerAsync(string URL);
      }   
    

    //later on, when I download the data: (URL is a provided string)

      string result = await DependencyService.Get<IServerCommunication> 
      ().GetFromServerAsync(URL);
    
       public async Task<string> GetFromServerAsync(string URL)
       {
        HttpClient client = await PreparedClientAsync();
    
        HttpResponseMessage response;
    
        try
        {
        response = await client.GetAsync(new Uri(URL));
    
        IBuffer buffer = await response.Content.ReadAsBufferAsync();
        DataReader reader = DataReader.FromBuffer(buffer);
        byte[] fileContent = new byte[reader.UnconsumedBufferLength];
        reader.ReadBytes(fileContent);
        string result = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
    
        return result;
        }
        catch (Exception ex)
        {
        return "error";
        }
        }
    
    
      private async Task<HttpClient> PreparedClientAsync()
      {
       var filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    
       filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
       filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
       filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
    
        HttpClient client = new HttpClient(filter);
    
        //I also handle other stuff here (client certificate, authentification), but the 
        lines above should allow the Httpclient to accept all certificates
    
        return client;
       }
    
    0 讨论(0)
提交回复
热议问题