-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProxyHttpMessageHandler.cs
89 lines (80 loc) · 2.86 KB
/
ProxyHttpMessageHandler.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
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace WebRequest.Elegant.Fakes
{
/// <summary>
/// The purpose is to assist during the unit testing.
/// </summary>
public class ProxyHttpMessageHandler : DelegatingHandler
{
public ProxyHttpMessageHandler()
: this(new HttpClientHandler())
{
}
public ProxyHttpMessageHandler(HttpMessageHandler messageHandler)
{
InnerHandler = messageHandler;
}
/// <summary>
/// Gets as a <see cref="HttpRequestMessage"/> the requests that have been sent during the collaboration.
/// </summary>
public List<HttpRequestMessage> Requests
{
get;
private set;
} = new List<HttpRequestMessage>();
/// <summary>
/// Gets as a string the requests that have been sent during the collaboration.
/// </summary>
public List<string> RequestsContent
{
get;
private set;
} = new List<string>();
/// <summary>
/// Gets as a string the responses that have been received during the collaboration.
/// </summary>
public List<string> ResponsesContent
{
get;
private set;
} = new List<string>();
/// <summary>
/// Gets as a <see cref="HttpResponseMessage"/> the responses that have been received during the collaboration.
/// </summary>
public List<HttpResponseMessage> Responses
{
get;
private set;
} = new List<HttpResponseMessage>();
/// <summary>
/// Works as a proxy sending requests to the server and receiving the responses.
/// </summary>
/// <param name="request">The request that has to be sent.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Simulated http response message.</returns>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Requests.Add(request);
var postContent = string.Empty;
if (request.Content != null)
{
postContent = await request.Content
.ReadAsStringAsync()
.ConfigureAwait(false);
}
RequestsContent.Add(postContent);
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
Responses.Add(response);
if (response.Content != null)
{
ResponsesContent.Add(
await response.Content.ReadAsStringAsync().ConfigureAwait(false)
);
}
return response;
}
}
}