• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Http.WebRequestHandler类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Net.Http.WebRequestHandler的典型用法代码示例。如果您正苦于以下问题:C# WebRequestHandler类的具体用法?C# WebRequestHandler怎么用?C# WebRequestHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



WebRequestHandler类属于System.Net.Http命名空间,在下文中一共展示了WebRequestHandler类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Persist

 public void Persist(TrackerData trackerData)
 {
     // setup the client
     // -   with a custome handler to approve all server certificates
     var handler = new WebRequestHandler
     {
         ServerCertificateValidationCallback =
             (sender, certificate, chain, errors) => true
     };
     try
     {
         using (var client = new HttpClient(handler))
         {
             // post it
             HttpResponseMessage httpResponseMessage = client.PostAsJsonAsync(_serviceUrl, trackerData).Result;
             if (!httpResponseMessage.IsSuccessStatusCode)
             {
                 Configurator.Configuration.Logger.Warn(string.Format("Data not persisted with status {0}",
                     httpResponseMessage.StatusCode));
             }
         }
     }
     catch (Exception ex)
     {
         Configurator.Configuration.Logger.Error(ex.Message, ex);
     }
 }
开发者ID:ksenthil,项目名称:Graphene,代码行数:27,代码来源:PersistToService.cs


示例2: execute

        static async Task execute(
                                    string authority,
                                    string resourceUri,
                                    string thisAppClientID,
                                    string thisAppKey,
                                    string epAddress
                                )
        {
            using (var handler = new WebRequestHandler())
            {
                handler.ServerCertificateValidationCallback += (sender, x509cert, chain, policyerrs) => { return true; };


                using (var client = new HttpClient(handler))
                {

                    var authToken = await getAuthToken(authority, 
                                                       resourceUri, 
                                                       thisAppClientID, 
                                                       thisAppKey);


                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authToken);
               //     client.DefaultRequestHeaders.Add("Authorization", "Bearer " + "BS HERE");
                    
                    var response = await client.GetAsync(new Uri(epAddress));

                    Console.WriteLine("ep: {0} - Response: {1}", epAddress, response.StatusCode);
                }

            }
        }
开发者ID:Renniesb,项目名称:AADNodeJWT,代码行数:34,代码来源:Program.cs


示例3: ProcessAttachment

        public async Task ProcessAttachment(long incidentId, string fileName)
        {
            String fileAsBase64 = Convert.ToBase64String(File.ReadAllBytes(fileName));
            AttachmentWrapper payload = new AttachmentWrapper();
            payload.Attachment = IncidentAttachment.CreateIncidentAttachment(Path.GetFileName(fileName), fileAsBase64);

            string createAttachementUri = "https://icm.ad.msft.net/api/cert/incidents(" + incidentId
                                          + ")/CreateAttachment";
            Logger.DebugFormat("CreateAttachementUri {0}", createAttachementUri);

            try
            {
                using (WebRequestHandler handler = new WebRequestHandler())
                {
                    handler.ClientCertificates.Add(certificate);

                    using (HttpClient client = new HttpClient(handler))
                    {
                        client.BaseAddress = new Uri(createAttachementUri);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var response = await client.PostAsJsonAsync(createAttachementUri, payload);
                        Logger.InfoFormat(response.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat(ex.ToString());
            }
        }
开发者ID:strince,项目名称:mail2bug,代码行数:31,代码来源:IcmODataClient.cs


示例4: HttpClientJsonRequestTest

        public async Task HttpClientJsonRequestTest()
        {
            var handler = new WebRequestHandler();
            //handler.Proxy = new WebProxy("http://localhost:8888/");
            //handler.Credentials = new NetworkCredential(uid, pwd);            

            var client = new HttpClient(handler);

            var postSnippet = new CodeSnippet()
            {
                UserId = "Bogus",
                Code = "string.Format('Hello World, I will own you!');",
                Comment = "World domination imminent"
            };

            // this isn't actually an API so the POST is ignored
            // but it always returns a JSON response 
            string url = "http://codepaste.net/recent?format=json";

            var response = await client.PostAsync(url, postSnippet,
                                                  new JsonMediaTypeFormatter(), null);

            Assert.IsTrue(response.IsSuccessStatusCode);

            var snippets = await response.Content.ReadAsAsync<List<CodeSnippet>>();
            Assert.IsTrue(snippets.Count > 0);

            foreach (var snippet in snippets)
            {
                if (string.IsNullOrEmpty(snippet.Code))
                    continue;
                Console.WriteLine(snippet.Code.Substring(0, Math.Min(snippet.Code.Length, 200)));
                Console.WriteLine("--");
            }
        }
开发者ID:RickStrahl,项目名称:WestwindToolkit,代码行数:35,代码来源:HttpUtilsTests.cs


示例5: Check

        public BuildStatusCollection Check()
        {
            var status = new BuildStatusCollection();
            string response = "NO RESPONSE";

            try
            {
                var webRequestHandler = new WebRequestHandler();
                if (!string.IsNullOrWhiteSpace(Settings.Default.TeamCityUser) && !string.IsNullOrWhiteSpace(Settings.Default.TeamCityPassword))
                {
                    webRequestHandler.Credentials = new NetworkCredential(Settings.Default.TeamCityUser, Settings.Default.TeamCityPassword);
                }
                using (var client = new HttpClient(webRequestHandler))
                {
                    client.BaseAddress = new Uri(Settings.Default.TeamCityUrl);
                    logger.Debug("Getting status from TeamCity at URL [{0}] with user [{1}] and password [{2}]", new Uri(client.BaseAddress, REQUEST_PATH), Settings.Default.TeamCityUser ?? "Anonymous",
                                 Settings.Default.TeamCityPassword ?? "N/A");
                    response = client.GetStringAsync(REQUEST_PATH).Result;
                    logger.Debug("Response from server is {0}", response);
                    return new BuildStatusCollection(response);
                }
            }
            catch (Exception err)
            {
                logger.ErrorException(
                    string.Format(
                        "Unexpected exception occured when checking status at TeamCity.  URL [{0}], User [{1}], Password [{2}], RawResponse [{3}]",
                        Settings.Default.TeamCityUrl ?? " NULL", Settings.Default.TeamCityUser ?? "Anonymous",
                        Settings.Default.TeamCityPassword ?? "N/A", response), err);
            }

            return status;
        }
开发者ID:tcabanski,项目名称:TeamCityBuildLight,代码行数:33,代码来源:BuildStatusChecker.cs


示例6: CreateWebClient

        public HttpClient CreateWebClient()
        {
            if(handler == null)
            {
                if (ClientCertificate == null)
                    throw new NullReferenceException("ClientCertificate is null.");

                if (ServerCertificateValidator == null)
                    throw new NullReferenceException("ServerCertificateValidator is null.");

                if (BaseUrl == null)
                    throw new NullReferenceException("BaseUrl is null.");

                handler = new WebRequestHandler();
                handler.ClientCertificateOptions = ClientCertificateOption.Manual;
                handler.ClientCertificates.Add(ClientCertificate);
                handler.ServerCertificateValidationCallback = ServerCertificateValidator;
            }

            if (client == null)
            {
                client = new HttpClient(handler);
                client.DefaultRequestHeaders.Add("x-devupdater-client-version", version.ToString()); // send version (next version will be able to reject older versions)
            }

            return client;
        }
开发者ID:jechtom,项目名称:DevUpdater,代码行数:27,代码来源:RemoteRepositoryServerContext.cs


示例7: Main

        static void Main(string[] args)
        {
            var handler = new WebRequestHandler();
            handler.ClientCertificates.Add(
                X509.CurrentUser
                    .My
                    .SubjectDistinguishedName
                    .Find("CN=client")
                    .First());

            //var handler = new HttpClientHandler
            //{
            //    ClientCertificateOptions = ClientCertificateOption.Automatic
            //};

            var client = new HttpClient(handler)
            {
                BaseAddress = new Uri("https://web.local:444/api/")
            };

            client.SetBasicAuthentication("bob", "bob");

            var result = client.GetStringAsync("identity").Result;
            Console.WriteLine(JArray.Parse(result));
        }
开发者ID:Bihari,项目名称:Thinktecture.IdentityModel,代码行数:25,代码来源:Program.cs


示例8: SystemNetHttpClientAdapter

        public SystemNetHttpClientAdapter(AdapterOptions options)
        {
            _autoRedirect = options.AutoRedirect;
            var handler = new WebRequestHandler
            {
                AllowAutoRedirect = !(AutoRedirect.AutoRedirectAndForwardAuthorizationHeader.Equals(options.AutoRedirect) ||
                                      AutoRedirect.DoNotAutoRedirect.Equals(options.AutoRedirect)),
                UseCookies = false,
            };

            if (options.CachePolicy.Cache)
            {
                handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
            }

            if (options.AcceptEncoding.AcceptGzipAndDeflate)
            {
                handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            }

            _client = new HttpClient(handler);

            if (options.Timeout != null)
            {
                _client.Timeout = options.Timeout.TimeSpan;
            }
        }
开发者ID:featurist,项目名称:Everest,代码行数:27,代码来源:SystemNetHttpClientAdapter.cs


示例9: Main

        //static Uri _baseAddress = new Uri(Constants.SelfHostBaseAddress);

        static void Main(string[] args)
        {
            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling Service\n".ConsoleYellow();

                    var handler = new WebRequestHandler();
                    handler.ClientCertificates.Add(
                        X509.
                        CurrentUser.
                        My.
                        SubjectDistinguishedName.
                        Find("CN=Client").First());

                    var client = new HttpClient(handler) { BaseAddress = _baseAddress };
                    
                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var identity = response.Content.ReadAsAsync<Identity>().Result;
                    identity.ShowConsole();
                });

                Console.ReadLine();
            }
        }
开发者ID:bencoveney,项目名称:Thinktecture.IdentityModel.40,代码行数:30,代码来源:Program.cs


示例10: RunAsync

        protected override async Task RunAsync(HttpApiContext context)
        {
            using (WebRequestHandler handler = new WebRequestHandler())
            {
                handler.UseCookies = false;
                handler.AllowAutoRedirect = false;
                handler.ServerCertificateValidationCallback = delegate { return true; };
                //handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
                handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip;
                using (HttpClient client = new HttpClient(handler))
                {
                    HttpRequestMessage request = Create(context.Request);

                    var response = await client.SendAsync(request);


                    var data = await response.Content.ReadAsByteArrayAsync();

                    context.Response = SetResponse(response, data);
                    var ct = response.Content.Headers.ContentType;
                    if (ct != null)
                    {
                        context.Response.ContentType = ct.ToString();
                    }

                    //context.Response.ContentType = response.Content.Headers.ContentType.ToString();
                }
            }
        }
开发者ID:neurospeech,项目名称:app-web-core,代码行数:29,代码来源:HttpProxyController.cs


示例11: getWebRequestHandlerWithCert

 private WebRequestHandler getWebRequestHandlerWithCert(string certFilename)
 {
     var cert = new X509Certificate2(certFilename, "");
     var clientHandler = new WebRequestHandler();
     clientHandler.ClientCertificates.Add(cert);
     return clientHandler;
 }
开发者ID:markbradshaw10,项目名称:API-NG-sample-code,代码行数:7,代码来源:AuthClient.cs


示例12: HttpClientAbstraction

 internal HttpClientAbstraction(HttpClient client, IAbstractionContext context, WebRequestHandler handler, bool ignoreSslErrors)
     : this(client, handler, ignoreSslErrors)
 {
     if (context.Logger.IsNotNull())
     {
         this.instanceLogger = context.Logger;
     }
     this.cancellationToken = context.CancellationToken;
 }
开发者ID:RossMerr,项目名称:azure-sdk-for-net,代码行数:9,代码来源:HttpClientAbstraction.cs


示例13: initHttpClientInstance

 private HttpClient initHttpClientInstance(WebRequestHandler clientHandler, string appKey, string baseUrl = DEFAULT_COM_BASEURL)
 {
     var client = new HttpClient(clientHandler);
     client.BaseAddress = new Uri(baseUrl);
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Add("X-Application", appKey);
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     return client;
 }
开发者ID:markbradshaw10,项目名称:API-NG-sample-code,代码行数:9,代码来源:AuthClient.cs


示例14: CreateHttpClient

 // We use the same HttpClient for all calls to the same subscription; this allows DNS and proxy details to be
 // cached across requests. Note that HttpClient allows parallel operations.
 internal static HttpClient CreateHttpClient (Subscription subscription, string msVersion, Func<IEnumerable<TraceListener>> listenerFunc)
 {
     var handler = new WebRequestHandler();
     handler.ClientCertificates.Add(subscription.ManagementCertificate);
     var logger = new LoggingHandler(handler, listenerFunc);
     var client = new HttpClient(logger, true);
     client.DefaultRequestHeaders.Add("x-ms-version", msVersion);
     return client;
 }
开发者ID:jamesmiles,项目名称:API,代码行数:11,代码来源:AzureRestClient.cs


示例15: CreateVMManagementClient

 /// <summary>
 /// Allan Alderman 1-10-2014
 /// Assembles a VM Managment client, attaching the correct management certificate.
 /// </summary>
 /// <returns>An HTTP client that is ready and authorized to issue commands to Azure's REST API.</returns>
 public static HttpClient CreateVMManagementClient()
 {
     if (_http != null) return _http;
     var handler = new WebRequestHandler();
     handler.ClientCertificates.Add(ConstructX509Certificate());
     _http = new HttpClient(handler) {BaseAddress = new Uri(AzureVmRestApiUri)};
     _http.DefaultRequestHeaders.Add("x-ms-version", "2013-08-01");
     return _http;
 }
开发者ID:GAAlderman,项目名称:Iris.Web.Scaling.Azure,代码行数:14,代码来源:SmapiCommandHandlerControllerUtils.cs


示例16: RunClient

        private static void RunClient()
        {
            // TEST CERTIFICATE ONLY, PLEASE REMOVE WHEN YOU REPLACE THE CERT WITH A REAL CERT
            // Perform the Server Certificate validation
            ServicePointManager.ServerCertificateValidationCallback += Program.RemoteCertificateValidationCallback;

            // set up the client without client certificate
            HttpClient client = new HttpClient();
            client.BaseAddress = _baseAddress;
            
            // set up the client with client certificate
            WebRequestHandler handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual; // this would pick from the Current user store
            handler.ClientCertificates.Add(GetClientCertificate());

            HttpClient clientWithClientCert = new HttpClient(handler);
            clientWithClientCert.BaseAddress = _baseAddress;
            HttpResponseMessage response;

            //// How to post a sample item with success
            SampleItem sampleItem = new SampleItem { Id = 1, StringValue = "hello from a new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting the first item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to post another sample item with success
            sampleItem = new SampleItem { Id = 2, StringValue = "hello from a second new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting a second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the two newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get an sample item with id = 2
            response = client.GetAsync("api/sample/2").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting the second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // Posting without client certificate will fail 
            sampleItem = new SampleItem { Id = 3, StringValue = "hello from a new sample item" };
            response = client.PostAsJsonAsync("api/sample/", sampleItem).Result;
            Console.WriteLine("Posting the third item without client certificate fails:\n" + response.StatusCode + "\n");
            response.Dispose();
        }
开发者ID:wk-j,项目名称:asp-samples,代码行数:57,代码来源:Program.cs


示例17: CreateHttpClient

        public static HttpClient CreateHttpClient()
        {
            var serviceAccount = System.Configuration.ConfigurationManager.AppSettings["RsApiServiceUser"];
            var serviceAccountPass = System.Configuration.ConfigurationManager.AppSettings["RsApiServiceUserPass"];
            /*
            var handler = new HttpClientHandler()
                              {
                                  // UseDefaultCredentials = true
                                  Credentials =
                                      new NetworkCredential(
                                      serviceAccount,
                                      serviceAccountPass, "NRECA")
                              };

            var handler = new HttpClientHandler()
            {
                UseDefaultCredentials = true

            };
            */
            WebRequestHandler handler;
            if (string.IsNullOrEmpty(serviceAccount))
            {
                handler = new WebRequestHandler
                {
                    UseDefaultCredentials = true

                };
            }
            else
            {
                handler = new WebRequestHandler
                {
                    // UseDefaultCredentials = true
                    Credentials =
                     new NetworkCredential(
                     serviceAccount,
                     serviceAccountPass, "NRECA")
                };
            }

            handler.PreAuthenticate = true;
            handler.UnsafeAuthenticatedConnectionSharing = true;

               handler.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;

            var rsHttpClient = new HttpClient(handler);
            var url = System.Configuration.ConfigurationManager.AppSettings["RsApiUrl"];
            rsHttpClient.BaseAddress = new Uri(url);
            rsHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json"));

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

            return rsHttpClient;
        }
开发者ID:chyno,项目名称:IntegrationTesting,代码行数:56,代码来源:HttpClientInstanceFactory.cs


示例18: CreateAuthenticationProvider

        public static IAuthenticationProvider CreateAuthenticationProvider(IAuthenticationInfo authenticationInfo, Uri baseAddress, TimeSpan? serviceTimeout = null, bool continueAsyncTasksOnCapturedContext = false, Action<HttpClient> postHttpClientInitializeAction = null)
        {
            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AppId)
            {
                return new AppIdAuthenticationProvider(authenticationInfo as AppIdAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AppRole)
            {
                return new AppRoleAuthenticationProvider(authenticationInfo as AppRoleAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.AwsEc2)
            {
                return new AwsEc2AuthenticationProvider(authenticationInfo as AwsEc2AuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.GitHub)
            {
                return new GitHubAuthenticationProvider(authenticationInfo as GitHubAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.LDAP)
            {
                return new LDAPAuthenticationProvider(authenticationInfo as LDAPAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.Certificate)
            {
                var certificationInfo = authenticationInfo as CertificateAuthenticationInfo;

                var handler = new WebRequestHandler();
                handler.ClientCertificates.Add(certificationInfo.ClientCertificate);

                return new CertificateAuthenticationProvider(certificationInfo, new HttpDataAccessManager(baseAddress, handler, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.Token)
            {
                return new TokenAuthenticationProvider(authenticationInfo as TokenAuthenticationInfo);
            }

            if (authenticationInfo.AuthenticationBackendType == AuthenticationBackendType.UsernamePassword)
            {
                return new UsernamePasswordAuthenticationProvider(authenticationInfo as UsernamePasswordAuthenticationInfo, new HttpDataAccessManager(baseAddress, serviceTimeout: serviceTimeout, postHttpClientInitializeAction: postHttpClientInitializeAction), continueAsyncTasksOnCapturedContext);
            }

            var customAuthenticationInfo = authenticationInfo as CustomAuthenticationInfo;

            if (customAuthenticationInfo != null)
            {
                return new CustomAuthenticationProvider(customAuthenticationInfo, continueAsyncTasksOnCapturedContext);
            }

            throw new NotSupportedException("The requested authentication backend type is not supported: " + authenticationInfo.AuthenticationBackendType);
        }
开发者ID:rajanadar,项目名称:VaultSharp,代码行数:56,代码来源:AuthenticationProviderFactory.cs


示例19: CertificateCredentials

        public CertificateCredentials(X509Certificate2 clientCertificate)
        {
            _handler = new WebRequestHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                UseDefaultCredentials = false
            };

            _handler.ClientCertificates.Add(clientCertificate);
        }
开发者ID:onecityuni,项目名称:Docker.DotNet,代码行数:10,代码来源:CertificateCredentials.cs


示例20: Main

        private static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                Console.WriteLine("Enter PIN: ");
                string pin = Console.ReadLine();

                WebRequestHandler handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);

                using (HttpClient client = new HttpClient(handler, true))
                {
                    client.BaseAddress = new Uri(string.Format(@"https://{0}:{1}", MachineName, RemotePort));

                    X509Store store = null;

                    try
                    {
                        var response = await client.GetAsync("certs/" + pin);
                        response.EnsureSuccessStatusCode();

                        byte[] rawCert = await response.Content.ReadAsByteArrayAsync();

                        X509Certificate2Collection certs = new X509Certificate2Collection();
                        certs.Import(rawCert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet);

                        store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                        store.Open(OpenFlags.ReadWrite);

                        X509Certificate2Collection oldCerts = new X509Certificate2Collection();

                        foreach (var cert in certs)
                        {
                            oldCerts.AddRange(store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false));
                        }
                        store.RemoveRange(certs);
                        store.AddRange(certs);
                        store.Close();

                        Console.WriteLine("Success");
                    }
                    catch (HttpRequestException e)
                    {
                        Console.WriteLine("Error communicating with vcremote. Make sure that vcremote is running in secure mode and that a new client cert has been generated.");
                    }
                    finally
                    {
                        if (store != null)
                        {
                            store.Close();
                        }
                    }
                }
            }).Wait();
        }
开发者ID:lsgxeva,项目名称:MIEngine,代码行数:55,代码来源:CertTool.cs



注:本文中的System.Net.Http.WebRequestHandler类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Http.WinHttpHandler类代码示例发布时间:2022-05-26
下一篇:
C# Http.StringContent类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap