Skip to content

Commit 790e19c

Browse files
authored
feat(ExampleProject): add HttpRequest example (#26)
1 parent fe7bc7d commit 790e19c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

src/ExampleProject/HttpRequest.cs

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Non-nullable member is uninitialized
2+
#pragma warning disable CS8618
3+
// ReSharper disable All
4+
5+
// Example from https://github.com/dotnet/csharplang/discussions/7325.
6+
7+
using System.Net.Http.Json;
8+
using System.Text.Json;
9+
using M31.FluentApi.Attributes;
10+
11+
namespace ExampleProject;
12+
13+
[FluentApi]
14+
public class HttpRequest
15+
{
16+
[FluentMember(0)]
17+
public HttpMethod Method { get; private set; }
18+
19+
[FluentMember(1)]
20+
public string Url { get; private set; }
21+
22+
[FluentCollection(2, "Header")]
23+
public List<(string, string)> Headers { get; private set; }
24+
25+
[FluentMember(3)]
26+
public HttpContent Content { get; private set; }
27+
28+
[FluentMethod(3)]
29+
public void WithJsonContent<T>(T body, Action<JsonSerializerOptions>? configureSerializer = null)
30+
{
31+
JsonSerializerOptions options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
32+
configureSerializer?.Invoke(options);
33+
Content = new StringContent(JsonSerializer.Serialize(body));
34+
}
35+
36+
[FluentMethod(4)]
37+
[FluentReturn]
38+
public HttpRequestMessage GetMessage()
39+
{
40+
HttpRequestMessage request = new HttpRequestMessage(Method, Url);
41+
request.Content = Content;
42+
Headers.ForEach(h => request.Headers.Add(h.Item1, h.Item2));
43+
return request;
44+
}
45+
}

src/ExampleProject/Program.cs

+16
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,22 @@
9898

9999
Console.WriteLine(JsonSerializer.Serialize(employee));
100100

101+
// HttpRequest
102+
//
103+
// Example from https://github.com/dotnet/csharplang/discussions/7325.
104+
//
105+
106+
HttpRequestMessage message = CreateHttpRequest
107+
.WithMethod(HttpMethod.Post)
108+
.WithUrl("https://example.com")
109+
.WithHeaders(("Accept", "application/json"), ("Authorization", "Bearer x"))
110+
.WithJsonContent(
111+
new { Name = "X", Quantity = 10 },
112+
opt => opt.PropertyNameCaseInsensitive = true)
113+
.GetMessage();
114+
115+
Console.WriteLine(JsonSerializer.Serialize(message));
116+
101117
// Node
102118
//
103119

0 commit comments

Comments
 (0)