Skip to content

Instantly share code, notes, and snippets.

@HamidMosalla
Created October 19, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HamidMosalla/27a1d66490cbd2a295264cd0e6362acd to your computer and use it in GitHub Desktop.
Save HamidMosalla/27a1d66490cbd2a295264cd0e6362acd to your computer and use it in GitHub Desktop.
An Api Request with Authorization header
static void Main(string[] args)
{
var response = Task.Run(() => MainAsync()).Result;
Console.WriteLine(response);
Console.ReadLine();
}
public static async Task<string> MainAsync()
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:5000");
var accessToken = await GetAccessToken();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync("/api/Product");
return $"Status Code: {response.StatusCode}\nContent: {await response.Content.ReadAsStringAsync()}";
}
}
public static async Task<string> GetAccessToken()
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:5000");
var httpContent = new StringContent("{Email: \"mosalla@gmail.com\", Password: \"123654\"}", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("/Token/Generate", httpContent);
return await response.Content.ReadAsStringAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment