SimpleREST.NET 0.1
A simple and minimal api framework for .net base on Express.js
Loading...
Searching...
No Matches
SimpleRestRequest.cs
Go to the documentation of this file.
1using System.Collections;
2using System.Collections.ObjectModel;
3using System.Diagnostics.CodeAnalysis;
4using System.Net;
5using System.Text;
6using System.Text.Json;
7using System.Text.Json.Nodes;
8using System.Text.Json.Serialization;
10
11namespace SimpleRest.Api;
12
24
26{
27 public string Endpoint { get; private set; } = "";
28 public object[]? Path { get; private set; }
29 public Dictionary<string, object?> Query { get; private set; } = new Dictionary<string, object?>();
30 public Dictionary<string, object?> Params { get; set; } = new Dictionary<string, object?>();
31
32 public SimpleRestBody Body { get; private set; }
33 public WebHeaderCollection Headers { get; private set; } = new WebHeaderCollection();
34 public string? ContentType { get; private set; }
35 public long ContentLength { get; private set; }
36 public SimpleRestMethod Method { get; private set; }
37 public string? UserAgent { get; private set; }
38 JsonSerializerOptions m_SerializerOptions;
39 private SimpleRestRequest() { }
40
42
44 public object? this[string key]
45 {
46 get => Params[key];
47 }
48
56 HttpListenerContext listenerContext, JsonSerializerOptions jsonOptions,
57 ISimpleRestEndpointFormatter? endpointFormatter = null
58 )
59 {
60 HttpListenerRequest contextRequest = listenerContext.Request;
62 request.m_SerializerOptions = jsonOptions;
63 if (contextRequest.QueryString.Count > 0)
64 {
65 request.Query =
66 contextRequest.QueryString.AllKeys.ToDictionary(
67 k => k ?? "",
68 k =>
69 {
70 object? value = contextRequest.QueryString[k]?.SafeDeserialize(contextRequest.QueryString[k], jsonOptions);
71 if (value is JsonElement element)
72 {
73 return element.ValueKind switch
74 {
75 JsonValueKind.Number when element.TryGetInt32(out int intValue) => intValue, // Integer
76 JsonValueKind.Number => element.GetDouble(), // Floating-point
77 JsonValueKind.String => element.GetString(), // String
78 JsonValueKind.True => true, // Boolean true
79 JsonValueKind.False => false, // Boolean false
80 JsonValueKind.Null => null, // Null
81 JsonValueKind.Object => element.Deserialize<JsonObject>(jsonOptions),
82 _ => throw new InvalidOperationException($"Unsupported JSON value: {value}"), // Handle unexpected types
83 };
84 }
85 return value;
86 }
87
88 );
89
90
91 }
92 else
93 {
94 request.Query = new Dictionary<string, object?>();
95 }
96
97 request.Body = new SimpleRestBody(contextRequest, request.m_SerializerOptions);
98 request.Headers = contextRequest
99 .Headers?.AllKeys.ToDictionary(k => k, k => contextRequest.Headers[k])
100 .ToWebHeaderCollection();
101 request.ContentType = contextRequest.ContentType;
102 request.ContentLength = contextRequest.ContentLength64;
103 string pathAndQuery = contextRequest.Url?.PathAndQuery ?? "/";
104 request.Endpoint =
105 (pathAndQuery.Contains('?') ? pathAndQuery?.Split("?")[0] : pathAndQuery) ?? "/";
106 Console.WriteLine("Endpoint:" + request.Endpoint);
107
108 request.Endpoint = endpointFormatter?.GetEndpoint(request.Endpoint) ?? request.Endpoint;
109 Console.WriteLine("Endpoint:" + request.Endpoint);
110
111 request.Method = Enum.Parse<SimpleRestMethod>(contextRequest.HttpMethod);
112 // Get the raw URL and extract the path
113 string? rawUrl = contextRequest.RawUrl;
114 string? path = rawUrl?.Split('?')[0]; // Exclude any query string
115 string[]? pathSegments = path?.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); // Split by slash
116 request.Path = pathSegments.Length <= 0 ? new string[] { "/" } : pathSegments;
117
118 return request;
119 }
120}
121
122//TODO seperate SimpleRestRequestBody from SimpleRestRequest in a smart way
128public class SimpleRestBody
129{
130 JsonSerializerOptions m_SerializerOptions;
131 public SimpleRestBody(string contents, JsonSerializerOptions jsonOptions)
132 {
133 Bytes = Encoding.UTF8.GetBytes(contents);
134 m_SerializerOptions = jsonOptions;
135 Content = contents;
136 }
137
142 public SimpleRestBody(HttpListenerRequest request, JsonSerializerOptions jsonOptions)
143 {
144 using (var memoryStream = new MemoryStream())
145 {
146 request.InputStream.CopyTo(memoryStream);
147 Bytes = memoryStream.ToArray();
148 }
149 m_SerializerOptions = jsonOptions;
150
151 Content = Encoding.UTF8.GetString(Bytes);
152 }
153
157 public string Content { get; private set; }
158
162 public byte[] Bytes { get; private set; }
163
171 public T? As<T>()
172 {
173 return GetContent<T>();
174 }
175
184 public TBody? GetContent<TBody>()
185 {
186 return JsonSerializer.Deserialize<TBody>(Content, m_SerializerOptions);
187 }
188}
189
190
The body of a SimpleRest.Api.SimpleRestRequest. This class encapsulates the content of an HTTP reques...
SimpleRestBody(string contents, JsonSerializerOptions jsonOptions)
TBody? GetContent< TBody >()
The function GetContent<TBody> deserializes the Content property into an object of type TBody .
SimpleRestBody(HttpListenerRequest request, JsonSerializerOptions jsonOptions)
Initializes a new instance of the SimpleRestBody class using the specified HttpListenerRequest.
T? As< T >()
The function As<T> returns the content as type T if T is a reference type.
byte[] Bytes
Gets the raw content of the request body as a byte array.
string Content
Gets the content of the request body as a UTF-8 encoded string.
The main class for all incoming request data. This is a wrapper for the HttpListenerRequest class....
Dictionary< string, object?> Query
Dictionary< string, object?> Params
static SimpleRestRequest FromHttpListenerContext(HttpListenerContext listenerContext, JsonSerializerOptions jsonOptions, ISimpleRestEndpointFormatter? endpointFormatter=null)
Factory function creating a Request object with all http request info stored on it.