-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
76 lines (63 loc) · 2.31 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using HttpClientLab;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp
{
public class Program
{
public static void Main(string[] args)
{
Run().GetAwaiter().GetResult();
}
public static async Task Run()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(b => b.AddConsole(c => c.IncludeScopes = true));
// Setup the HttpClientFactory to mock the behaviour
serviceCollection.AddHttpClientBehaviour(out var httpClientBehaviour);
//define the behaviour
httpClientBehaviour
.SetupForAnyClient()
.ForAnyRequest()
.Returns(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Hello world!")
});
serviceCollection.AddHttpClient<GitHubClient>(c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
c.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (trust me, I'm really Mozilla!)");
});
var services = serviceCollection.BuildServiceProvider();
var github = services.GetRequiredService<GitHubClient>();
var something = await github.GetSomething();
Console.WriteLine(something);
Debug.Assert(something == "Hello world!");
if (Debugger.IsAttached)
{
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
private class GitHubClient
{
public GitHubClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
private HttpClient _httpClient;
public async Task<string> GetSomething()
{
var response = await _httpClient.GetAsync("/");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
}
}