From 8bf49be9f6ab3777c1dd68cb577bc40d20e2542d Mon Sep 17 00:00:00 2001 From: Kevin Schaal Date: Mon, 17 Jun 2024 20:43:21 +0200 Subject: [PATCH] feat(ExampleProject): add HttpRequest example --- src/ExampleProject/HttpRequest.cs | 45 +++++++++++++++++++++++++++++++ src/ExampleProject/Program.cs | 16 +++++++++++ 2 files changed, 61 insertions(+) create mode 100644 src/ExampleProject/HttpRequest.cs diff --git a/src/ExampleProject/HttpRequest.cs b/src/ExampleProject/HttpRequest.cs new file mode 100644 index 0000000..3bf4235 --- /dev/null +++ b/src/ExampleProject/HttpRequest.cs @@ -0,0 +1,45 @@ +// 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 body, Action? configureSerializer = null) + { + JsonSerializerOptions options = new JsonSerializerOptions(JsonSerializerDefaults.Web); + configureSerializer?.Invoke(options); + Content = new StringContent(JsonSerializer.Serialize(body)); + } + + [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; + } +} \ No newline at end of file diff --git a/src/ExampleProject/Program.cs b/src/ExampleProject/Program.cs index c547b81..645728c 100644 --- a/src/ExampleProject/Program.cs +++ b/src/ExampleProject/Program.cs @@ -98,6 +98,22 @@ Console.WriteLine(JsonSerializer.Serialize(employee)); +// HttpRequest +// +// Example from https://github.com/dotnet/csharplang/discussions/7325. +// + +HttpRequestMessage message = CreateHttpRequest + .WithMethod(HttpMethod.Post) + .WithUrl("https://example.com") + .WithHeaders(("Accept", "application/json"), ("Authorization", "Bearer x")) + .WithJsonContent( + new { Name = "X", Quantity = 10 }, + opt => opt.PropertyNameCaseInsensitive = true) + .GetMessage(); + +Console.WriteLine(JsonSerializer.Serialize(message)); + // Node //