当前位置: 首页>>代码示例>>C#>>正文


C# HttpClient.SetBasicAuthentication方法代码示例

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


在下文中一共展示了HttpClient.SetBasicAuthentication方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            var localClient = new HttpClient();
            localClient.BaseAddress = new Uri("https://windows8vm/ngmd/api/");
            localClient.SetBasicAuthentication("cw", "cw");

            var cloudClient = new HttpClient();
            cloudClient.BaseAddress = new Uri("https://demo.christianweyer.net/api/");
            cloudClient.SetBasicAuthentication("cw", "cw");

            while (true)
            {
                Console.WriteLine("Calling 'personalization'");
                localClient.GetAsync("personalization");
                cloudClient.GetAsync("personalization");
                Console.WriteLine("Calling 'articles'");
                localClient.GetAsync("articles");
                cloudClient.GetAsync("articles");
                Console.WriteLine("Calling 'images'");
                localClient.GetAsync("images");
                cloudClient.GetAsync("images");
                Console.WriteLine("Calling 'statistics'");
                localClient.GetAsync("statistics");
                cloudClient.GetAsync("statistics");

                Thread.Sleep(10000);
            }
        }
开发者ID:jdmonty,项目名称:myProducts-End-to-End,代码行数:28,代码来源:Program.cs

示例2: Http_Post_Order

        public void Http_Post_Order()
        {
            var uri = "http://localhost/NortwindApi/";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.SetBasicAuthentication("[email protected]", "Wayne!");

                var model = new OrderModel()
                {
                    CustomerID = "VINET",
                    ShipCity = "Boston",
                    IsShipped = true
                };

                HttpResponseMessage response = client.PostAsJsonAsync("api/orders", model).Result;

                Assert.IsTrue(response.IsSuccessStatusCode);

                var content = response.Content.ReadAsStringAsync().Result;

                Assert.IsTrue(!String.IsNullOrEmpty(content));

                var order = JsonConvert.DeserializeObject<Order>(content);

                Assert.IsNotNull(order);
            }
        }
开发者ID:WorldWayno,项目名称:NorthwindStore,代码行数:29,代码来源:ApiTests.cs

示例3: RequestSessionToken

        private static string RequestSessionToken()
        {
            "Requesting session token\n".ConsoleYellow();

            var client = new HttpClient { BaseAddress = _baseAddress };
            client.SetBasicAuthentication("bob", "bob");

            var response = client.GetAsync("token").Result;
            response.EnsureSuccessStatusCode();

            var tokenResponse = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(tokenResponse);
            var token = json["access_token"].ToString();
            var expiresIn = int.Parse(json["expires_in"].ToString());
            var expiration = DateTime.UtcNow.AddSeconds(expiresIn);

            "\nSession Token:".ConsoleRed();
            Console.WriteLine(json.ToString());

            "\nExpiration:".ConsoleRed();
            Console.WriteLine(expiration.ToLongDateString() + " " + expiration.ToLongTimeString());

            //DecodeSessionToken(token);
            return token;
        }
开发者ID:kostebudinoski,项目名称:Thinktecture.IdentityModel.45,代码行数:25,代码来源:Program.cs

示例4: Main

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

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

            var client = new HttpClient(handler) {
                BaseAddress = _baseAddress
            };

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

            while (true)
            {
                Helper.Timer(() =>
                {
                    "Calling service.".ConsoleYellow();

                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

                    var claims = response.Content.ReadAsAsync<ViewClaims>().Result;
                    Helper.ShowConsole(claims);
                });

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

示例5: LogIn

        public async Task<ActionResult> LogIn(UsersLogInModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(Constants.ApiBaseUri);
                httpClient.SetBasicAuthentication(model.Username, model.Password);

                var response = await httpClient.GetAsync("token");

                if (response.IsSuccessStatusCode)
                {
                    var tokenResponse = await response.Content.ReadAsStringAsync();
                    var json = JObject.Parse(tokenResponse);
                    var token = json["access_token"].ToString();

                    Session[Constants.SessionTokenKey] = token;
                    
                    FormsAuthentication.SetAuthCookie(model.Username, createPersistentCookie: true);
                    return Redirect("~/");
                }
                else // could check specific error code here
                {
                    ModelState.AddModelError("", "The username and password provided do not match any accounts on record.");
                    return View();
                }
            }
        }
开发者ID:benfoster,项目名称:ApiDogFood,代码行数:32,代码来源:UsersController.cs

示例6: RevokeRefreshToken

        public async Task<ActionResult> RevokeRefreshToken()
        {
            var refreshToken = (User as ClaimsPrincipal).FindFirst("refresh_token").Value;
            var client = new HttpClient();
            client.SetBasicAuthentication("codeclient", "secret");

            var postBody = new Dictionary<string, string>
            {
                { "token", refreshToken },
                { "token_type_hint", "refresh_token" }
            };

            var result = await client.PostAsync(Constants.TokenRevocationEndpoint, new FormUrlEncodedContent(postBody));

            return RedirectToAction("Index");
        }
开发者ID:ryanmar,项目名称:IdentityServer3.Samples,代码行数:16,代码来源:AppController.cs

示例7: RequestSessionToken

        private static string RequestSessionToken()
        {
            "Requesting session token\n".ConsoleYellow();

            var client = new HttpClient { BaseAddress = _baseAddress };
            client.SetBasicAuthentication("bob", "bob");

            var response = client.GetAsync("token").Result;
            response.EnsureSuccessStatusCode();

            var tokenResponse = response.Content.ReadAsStringAsync().Result;
            var json = JObject.Parse(tokenResponse);
            var token = json["access_token"].ToString();
            
            "\nSession Token:".ConsoleRed();
            Console.WriteLine(json.ToString());

            return token;
        }
开发者ID:cgsosc,项目名称:Thinktecture.IdentityModel.45,代码行数:19,代码来源:Program.cs

示例8: IntrospectionClient

        public IntrospectionClient(string endpoint, string clientId = "", string clientSecret = "", HttpMessageHandler innerHttpMessageHandler = null)
        {
            if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentNullException("endpoint");
            if (innerHttpMessageHandler == null) innerHttpMessageHandler = new HttpClientHandler();

            _client = new HttpClient(innerHttpMessageHandler)
            {
                BaseAddress = new Uri(endpoint)
            };

            _client.DefaultRequestHeaders.Accept.Clear();
            _client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            if (!string.IsNullOrWhiteSpace(clientId))
            {
                _client.SetBasicAuthentication(clientId, clientSecret);
            }
        }
开发者ID:sparraguerra,项目名称:IdentityModel,代码行数:19,代码来源:IntrospectionClient.cs

示例9: Main

        static void Main()
        {
            var address = "http://localhost:925/";

            using (WebApp.Start<Startup>(address))
            {
                var client = new HttpClient();
                var response = client.GetAsync(address + "test").Result;
                Console.WriteLine(response.StatusCode);

                Console.WriteLine();
                Console.WriteLine("Next request sets basic authentication password");

                client.SetBasicAuthentication("filip", "abc");
                var response2 = client.GetAsync(address + "test").Result;
                Console.WriteLine(response2.StatusCode);

                Console.ReadLine();
            }
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:20,代码来源:Program.cs

示例10: CallTokenEndpointAsync

        public async static Task<OidcTokenResponse> CallTokenEndpointAsync(Uri tokenEndpoint, Uri redirectUri, string code, string clientId, string clientSecret)
        {
            var client = new HttpClient
            {
                BaseAddress = tokenEndpoint
            };

            client.SetBasicAuthentication(clientId, clientSecret);

            var parameter = new Dictionary<string, string>
                {
                    { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.AuthorizationCode },
                    { OAuth2Constants.Code, code },
                    { OAuth2Constants.RedirectUri, redirectUri.AbsoluteUri }
                };

            var response = await client.PostAsync("", new FormUrlEncodedContent(parameter));
            response.EnsureSuccessStatusCode();

            var json = JObject.Parse(await response.Content.ReadAsStringAsync());
            return json.ToObject<OidcTokenResponse>();
        }
开发者ID:Rameshcyadav,项目名称:Thinktecture.IdentityModel.45,代码行数:22,代码来源:OidcClient.cs

示例11: CallTokenEndpoint

        public static OidcTokenResponse CallTokenEndpoint(Uri tokenEndpoint, Uri redirectUri, string code, string clientId, string clientSecret)
        {
            var client = new HttpClient
            {
                BaseAddress = tokenEndpoint
            };

            client.SetBasicAuthentication(clientId, clientSecret);

            var parameter = new Dictionary<string, string>
                {
                    { "grant_type", "authorization_code" },
                    { "code", code },
                    { "redirect_uri", redirectUri.AbsoluteUri }
                };

            var response = client.PostAsync("", new FormUrlEncodedContent(parameter)).Result;
            response.EnsureSuccessStatusCode();

            var json = JObject.Parse(response.Content.ReadAsStringAsync().Result);
            return json.ToObject<OidcTokenResponse>();
        }
开发者ID:pksorensen,项目名称:Thinktecture.IdentityServer.v2,代码行数:22,代码来源:OidcClient.cs

示例12: Http_Get_Orders

        public void Http_Get_Orders()
        {
            var uri = "http://localhost/NortwindApi/";
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.SetBasicAuthentication("[email protected]", "Wayne!");

                HttpResponseMessage response = client.GetAsync("api/orders").Result;

                Assert.IsTrue(response.IsSuccessStatusCode);

                var content = response.Content.ReadAsStringAsync().Result;

                Assert.IsTrue(!String.IsNullOrEmpty(content));

                var orders = JsonConvert.DeserializeObject<IEnumerable<Order>>(content);

                Assert.IsTrue(orders.Any());
            }
        }
开发者ID:WorldWayno,项目名称:NorthwindStore,代码行数:22,代码来源:ApiTests.cs

示例13: Logout

        public HttpResponseMessage Logout([FromBody] LogoutViewModel input)
        {
            ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;

            var Name = ClaimsPrincipal.Current.Identity.Name;
            var Name1 = User.Identity.Name;

            var userName = principal.Claims.Where(c => c.Type == "sub").Single().Value;
            var a = HttpContext.Current.GetOwinContext();
            var b = a.Authentication;

            var client = new HttpClient();
            client.SetBasicAuthentication("carbon", "21B5F798-BE55-42BC-8AA8-0025B903DC3B");
            var postBody = new System.Collections.Generic.Dictionary<string, string>
            {
            { "token", input.Access_Token },
            //{ "token_type_hint", "refresh_token" }
            { "token_type_hint", "access_token" }
            };

            if (!string.IsNullOrEmpty(input.Access_Token))
            {
                var result = client.PostAsync("https://HFL0100:44333/connect/revocation", new FormUrlEncodedContent(postBody)).Result;
            }

            postBody = new System.Collections.Generic.Dictionary<string, string>
            {
            { "token", input.Refresh_Token },
            { "token_type_hint", "refresh_token" }
            //{ "token_type_hint", "access_token" }
            };

            if (!string.IsNullOrEmpty(input.Refresh_Token))
            {
                var result2 = client.PostAsync("https://HFL0100:44333/connect/revocation", new FormUrlEncodedContent(postBody)).Result;
            }
            var response2 = new HttpResponseMessage(HttpStatusCode.OK);
            var test = Request.Headers.GetCookies("Halo-Secure").SingleOrDefault();
            if (test != null)
            {
                test.Expires = DateTimeOffset.Now.AddDays(-1);
                response2.Headers.AddCookies(new CookieHeaderValue[] { test });
            }
            return response2;
        }
开发者ID:okusnadi,项目名称:IdentityServer3_WebApi_AngularJs_SSO_BearerToken,代码行数:45,代码来源:LoginController.cs


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