-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathHttpRequest.cs
58 lines (47 loc) · 1.54 KB
/
HttpRequest.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
// Non-nullable member is uninitialized
#pragma warning disable CS8618
// ReSharper disable All
// Example from https://github.com/dotnet/csharplang/discussions/7325.
using System.Net.Http.Json;
using System.Text.Json;
using M31.FluentApi.Attributes;
namespace ExampleProject;
[FluentApi]
public class HttpRequest
{
[FluentMember(0)]
public HttpMethod Method { get; private set; }
[FluentMember(1)]
public string Url { get; private set; }
[FluentCollection(2, "Header")]
public List<(string, string)> Headers { get; private set; }
[FluentMember(3)]
public HttpContent Content { get; private set; }
[FluentMethod(3)]
public void WithJsonContent<T>(T body, Action<JsonSerializerOptions>? configureSerializer = null)
{
JsonSerializerOptions options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
configureSerializer?.Invoke(options);
Content = new StringContent(JsonSerializer.Serialize(body));
}
[FluentMethod(3)]
public void WithoutContent()
{
}
[FluentMethod(4)]
[FluentReturn]
public HttpRequestMessage GetMessage()
{
HttpRequestMessage request = new HttpRequestMessage(Method, Url);
request.Content = Content;
Headers.ForEach(h => request.Headers.Add(h.Item1, h.Item2));
return request;
}
[FluentMethod(4)]
[FluentReturn]
public async Task<HttpResponseMessage> SendAsync(HttpClient client)
{
HttpRequestMessage request = GetMessage();
return await client.SendAsync(request);
}
}