本文整理汇总了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);
}
}
示例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);
}
}
示例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;
}
示例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();
}
}
示例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();
}
}
}
示例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");
}
示例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;
}
示例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);
}
}
示例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();
}
}
示例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>();
}
示例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>();
}
示例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());
}
}
示例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