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


C# HttpClient.SetToken方法代码示例

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


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

示例1: CallService

        private static void CallService(string token)
        {
            var client = new HttpClient { BaseAddress = _baseAddress };

            client.SetToken("Session", token);

            // some alternative header for session token 
            //client.DefaultRequestHeaders.Add("X-Session", "Session " + token);

            while (true)
            {
                "Calling service.".ConsoleYellow();

                Helper.Timer(() =>
                {
                    var response = client.GetAsync("identity").Result;
                    response.EnsureSuccessStatusCode();

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

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

示例2: Main

        static void Main(string[] args)
        {
            var tokenClient = new TokenClient("tokenService");
            XmlElement tokenXml = tokenClient.GetToken("urn:claimsdemo:http45mvc");
            string encodedToken = HeaderEncoding.EncodeBase64(tokenXml.OuterXml);

            string serviceEndpoint = ConfigurationManager.AppSettings["ServiceEndpoint"];

            var client = new System.Net.Http.HttpClient { BaseAddress = new Uri(serviceEndpoint) };
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SAML", tokenXml.OuterXml);
            client.SetToken("SAML", encodedToken);

            HttpResponseMessage response = client.GetAsync("api/DemoService/WhoAmI").Result;
            response.EnsureSuccessStatusCode();

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

            Console.WriteLine(content);

            //string whoAmIresult = channel.WhoAmI();
            //Console.WriteLine(whoAmIresult);

            //string restrictedMethodResult = channel.RestrictedMethod();
            //Console.WriteLine(restrictedMethodResult);

            Console.ReadLine();
        }
开发者ID:nordvall,项目名称:WifExamples,代码行数:27,代码来源:Program.cs

示例3: CallService

        private static void CallService(string token)
        {
            var client = new HttpClient
            {
                BaseAddress = _baseAddress
            };

            client.SetToken(Constants.IdSrv.SamlScheme, token);

            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,代码行数:25,代码来源:Program.cs

示例4: buttonCallService_Click

        private void buttonCallService_Click(object sender, EventArgs e)
        {
            textBoxServiceResponse.Text = string.Empty;
            try
            {
                string output = string.Empty;
                bool includeToken = checkBoxIncludeBearerToken.Checked;
                string acceptHeader = textBoxAcceptHeader.Text;
                string accessToken = textBoxToken.Text;
                string verb = textBoxHttpVerb.Text;
                string url = string.Format("{0}?api_key={1}", textBoxServiceUrl.Text, textBoxMasheryApiKey.Text);

                using (var client = new HttpClient())
                {
                    //Add default headers for every request from this http client
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader));
                    if (includeToken)
                        client.SetToken("Bearer", accessToken);

                    //Create specific request to send
                    HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(verb), url);

                    //Add specific header to this request
                    request.Headers.Add("x-cim-RequestId", Guid.NewGuid().ToString());

                    //Send request
                    HttpResponseMessage response = client.SendAsync(request).Result;
                    if(response.IsSuccessStatusCode)
                    {
                        string test = response.Content.ReadAsStringAsync().Result;
                        output = test;
                    }
                    else{
                        output = string.Format("StatusCode: {0}", response.StatusCode.ToString());
                    }
                }

                textBoxServiceResponse.Text = output;

            }
            catch(System.Exception exp)
            {
                MessageBox.Show(string.Format("{0}", exp.ToString()));
            }
        }
开发者ID:RachidFR,项目名称:RestWithOAuthSamples,代码行数:45,代码来源:Form1.cs

示例5: CallServiceButton_Click

        private void CallServiceButton_Click(object sender, RoutedEventArgs e)
        {
            var client = new HttpClient
            {
                BaseAddress = _baseAddress
            };

            client.SetToken(Constants.ACS.Scheme, _token);

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

            var claims = response.Content.ReadAsAsync<ViewClaims>().Result;
            var sb = new StringBuilder(128);

            foreach (var claim in claims)
            {
                sb.AppendFormat(" {0}\n  {1}\n\n", claim.Type, claim.Value);
            }

            OutputTextBox.Text = sb.ToString();
        }
开发者ID:Rameshcyadav,项目名称:Thinktecture.IdentityModel.45,代码行数:22,代码来源:MainWindow.xaml.cs

示例6: buttonGetOAuthToken_Click

        private void buttonGetOAuthToken_Click(object sender, EventArgs e)
        {
            textBoxToken.Text = string.Empty;
            try
            {
                // Getting a Token
                string uri = textBoxTokenEndpoint.Text;
                string clientid = textBoxClientId.Text;
                string secret = textBoxSecret.Text;
                string theToken = string.Empty;
                long HowLongTillExpires = long.MinValue;

                if(radioButtonThinkTecture.Checked)
                {
                    // Using the Thinktecture.IdentityModel.Client
                    var client = new OAuth2Client(
                        new Uri(uri),
                        clientid,
                        secret);

                    // For Thinktecture the "scope" request is passed in.
                    var response = client.RequestClientCredentialsAsync("read write").Result;

                    // At this point we now have the AccessToken in the response
                    theToken = response.AccessToken;
                    HowLongTillExpires = response.ExpiresIn;
                }
                else if(radioButtonStandardHttpClient.Checked)
                {
                    // Using standard http, we can make the call with Basic Authorization header
                    // We need to encode the "scope" as formUrlEncoded body
                    // First prepare the Base64Encode string for Basic Auth
                    string data = string.Format("{0}:{1}", clientid, secret);
                    byte[] binaryData = System.Text.Encoding.UTF8.GetBytes(data);
                    string authorizationString = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

                    using (var client = new HttpClient())
                    {
                        //Add Basic Authorization header for call to get OAuth token.
                        client.SetToken("Basic", authorizationString);

                        //Create specific request to send
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);

                        //Pass in oAuth "grant_type" as "client credentials" and "scope" as "read write"
                        //These must be application-form-url-encoded
                        List<KeyValuePair<string, string>> bodyContentList = new List<KeyValuePair<string, string>>();
                        bodyContentList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                        bodyContentList.Add(new KeyValuePair<string, string>("scope", "read write"));
                        request.Content = new FormUrlEncodedContent(bodyContentList);

                        //Send request
                        HttpResponseMessage response = client.SendAsync(request).Result;
                        if (response.IsSuccessStatusCode)
                        {
                            string oAuthResponseString = response.Content.ReadAsStringAsync().Result;

                            //An example of using dynamic keyword and accessing properties ("access_token" and "expires_in") at runtime.
                            dynamic oAuthToken = JsonConvert.DeserializeObject(oAuthResponseString);
                            theToken = oAuthToken.access_token;
                            HowLongTillExpires = oAuthToken.expires_in;
                        }
                        else
                        {
                            throw new System.Exception("Unable to acquire token.");
                        }
                    }

                }
                else
                {
                    throw new Exception("Invalid Client selected");
                }

                textBoxToken.Text = theToken;
                textBoxExpiresInSeconds.Text = HowLongTillExpires.ToString();

            }
            catch(System.Exception exp)
            {
                textBoxToken.Text = string.Format("Unable to get token.{0}{1}", System.Environment.NewLine, exp.ToString());
            }
        }
开发者ID:RachidFR,项目名称:RestWithOAuthSamples,代码行数:83,代码来源:Form1.cs

示例7: api_Click

        private async void api_Click(object sender, RoutedEventArgs e)
        {
            var baseAddress = Sample.Constants.AspNetWebApiSampleApiUsingPoP;

            var signature = new RS256Signature(_provider);
            var signingHandler = new HttpSigningMessageHandler(signature);

            var client = new HttpClient(signingHandler)
            {
                BaseAddress = new Uri(baseAddress)
            };
            
            client.SetToken("PoP", _result?.AccessToken);

            var response = await client.GetAsync("identity");

            var sb = new StringBuilder(128);
            sb.AppendLine($"{(int)response.StatusCode}, {response.StatusCode}");
            var json = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
                var values = JArray.Parse(json);
                foreach (JObject item in values)
                {
                    sb.AppendLine($"{item["type"].ToString()}, {item["value"].ToString()}");
                }
            }
            else
            {
                sb.AppendLine(json);
            }

            IdentityTextBox.Text = sb.ToString();
        }
开发者ID:RobGibbens,项目名称:IdentityServer3.Samples,代码行数:34,代码来源:MainWindow.xaml.cs


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