Created
October 19, 2017 03:05
-
-
Save HamidMosalla/27a1d66490cbd2a295264cd0e6362acd to your computer and use it in GitHub Desktop.
An Api Request with Authorization header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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